1268 and a combination of K
Base Time Limit: 1 second Space Limit: 131072 KB Score: 20Difficulty
: Level 3 Algorithm Questions
collect
focus on
Given an array A consisting of N positive integers, find out whether some of them can be selected so that their sum is K. If yes, output: "Yes", otherwise output "No".
Input
Line 1: 2 numbers N, K, N is the length of the array, K is the sum to be judged (2 <= N <= 20, 1 <= K <= 10^9) Lines 2 - N + 1: 1 number per line, corresponding to array element A[i] (1 <= A[i] <= 10^6)
Output
If yes, output: "Yes", otherwise output "No".
Input example
5 13 2 4 6 8 10
Output example
No
The number is small, you can do it directly, use a set to store the current sum, and add it to the number in the set every time you traverse a number. Of course, only those smaller than k are put into the set, which can be calculated less.
1 #include <bits/stdc++.h> 2 using namespace std; 3 int a[22]; 4 int main() { 5 int n, k; 6 set<int> st[2]; 7 set<int> ::iterator it; 8 cin >> n >> k; 9 int last = 0; 10 for(int i = 1; i <= n; i ++) cin >> a[i]; 11 for(int i = 1; i <= n; i ++) { 12 last = 1 - last; 13 it = st[1-last].begin(); 14 for(; it != st[1-last].end(); ++it) { 15 if((*it)+a[i] < k) { 16 st[last].insert((*it)+a[i]); 17 } else if((*it)+a[i] == k) return 0*printf("Yes\n"); 18 st[last].insert((*it)); 19 } 20 st[last].insert(a[i]); 21 } 22 if(st[last].count(k)) printf("Yes\n"); 23 else printf("No\n"); 24 return 0; 25 }