og86

subset_sum

May 29th, 2023
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. // Online C++ compiler to run C++ program online
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. bool func(vector<int> & arr, int n, int k){
  6. vector<bool> prev(k+1, 0), cur(k+1, 0);
  7.  
  8. prev[0] = cur[0] = true;
  9. if(arr[0] <= k) prev[arr[0]] = true;
  10.  
  11. for(int ind=1; ind<n; ind++){
  12. for(int target=1; target<=k; target++){
  13.  
  14. bool notTake = prev[target];
  15. bool take = false;
  16.  
  17. if(arr[ind] <= target) take = prev[target-arr[ind]];
  18. cur[target] = take | notTake;
  19. }
  20. prev = cur;
  21. }
  22.  
  23. return prev[k];
  24. }
  25.  
  26. int main() {
  27. // Write C++ code here
  28. int n, sum{0};
  29. cin>>n;
  30. vector<int> v(n);
  31. for(int i = 0; i < n; i++){
  32. cin>>v[i];
  33. sum += v[i];
  34. }
  35. if(sum%2) { cout<<"NO"; return 0; }
  36.  
  37. if(func(v, n, sum/2)){
  38. cout<<"YES";
  39. }
  40. else{
  41. cout<<"NO";
  42. }
  43. return 1;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment