fragment-header
fragment-markdown
홈
로그인
로그아웃
내 블로그
설정
로그인
백준 4680 (C++) Sum It Up
최초 업로드: 2025-09-22 07:03:03
최근 수정 시간: 2025-09-22 08:10:12
게시자: rlatjwls3333
카테고리: 백준
조회수: 6
# [Silver II] Sum It Up [문제 링크](https://www.acmicpc.net/problem/4680) ## 문제 설명 <p>Given a specified total t and a list of n integers, find all distinct sums using numbers from the list that add up to t. For example, if t = 4, n = 6, and the list is [4,3,2,2,1,1], then there are four different sums that equal 4: 4, 3+1, 2+2, and 2+1+1. (A number can be used within a sum as many times as it appears in the list, and a single number counts as a sum.) Your job is to solve this problem in general.</p> ## 입력 <p>The input file will contain one or more test cases, one per line. Each test case contains t, the total, followed by n, the number of integers in the list, followed by n integers x<sub>1</sub>,...,x<sub>n</sub>. If n = 0 it signals the end of the input; otherwise, t will be a positive integer less than 1000, n will be an integer between 1 and 12 (inclusive), and x<sub>1</sub>, . . . , x<sub>n</sub> will be positive integers less than 100. All numbers will be separated by exactly one space. The numbers in each list appear in nonincreasing order, and there may be repetitions.</p> ## 출력 <p>For each test case, first output a line containing ‘Sums of ’, the total, and a colon. Then output each sum, one per line; if there are no sums, output the line ‘NONE’. The numbers within each sum must appear in nonincreasing order. A number may be repeated in the sum as many times as it was repeated in the original list. The sums themselves must be sorted in decreasing order based on the numbers appearing in the sum. In other words, the sums must be sorted by their first number; sums with the same first number must be sorted by their second number; sums with the same first two numbers must be sorted by their third number; and so on. Within each test case, all sums must be distinct; the same sum cannot appear twice.</p> ## 풀이 조합을 구하는 것이라 백트래킹으로 충분히 시간 내에 돕니다. set에 저장하여 중복처리와 정렬을 해주었습니다. ``` c++ #include<bits/stdc++.h> using namespace std; int t, n, x[12]; vector<int> vis; set<vector<int>, greater<vector<int>>> res; void back(int depth=0, int sum=0, int cur=0) { if(sum==t) { res.insert(vis); return; } for(int i=cur;i<n;i++) { if(sum+x[i]<=t) { vis.push_back(x[i]); back(depth+1, sum+x[i], i+1); vis.pop_back(); } } } int main() { ios::sync_with_stdio(0); cin.tie(0); while(true) { cin >> t >> n; for(int i=0;i<n;i++) cin >> x[i]; if(!n) break; res = {}; back(); cout << "Sums of " << t <<":\n"; if(res.empty()) { cout << "NONE\n"; } else { for(auto elements : res) { for(int i=0;i<elements.size();i++) { if(i!=0) cout << '+'; cout << elements[i]; } cout << '\n'; } } } } ```