spider68

subsetsum for time

Mar 12th, 2020
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. bool subsetsum(int arr[],int n,int s)
  4. {
  5. int i,j;
  6. bool a[n+1][s+1];
  7. for(i=0;i<=n;i++)
  8. {
  9. for(j=0;j<=s;j++)
  10. {
  11. if(j==0)a[i][j]=true;
  12. else{
  13. if(i==0)a[i][j]=false;
  14. else{
  15. if(arr[i-1]>j)a[i][j]=a[i-1][j];
  16. else{
  17. a[i][j]=a[i-1][j]||a[i-1][j-arr[i-1]];
  18. }
  19. }
  20. }
  21. }
  22. }
  23. return a[n][s];
  24. }
  25. int main()
  26. {
  27. int i,j,t,m,n;
  28. cin>>t;
  29. while(t--)
  30. {
  31. int s=0;
  32. cin>>n;
  33. int a[n];
  34. for(i=0;i<n;i++){cin>>a[i]; s+=a[i];}
  35. if(s%2==1){cout<<"NO\n"; continue;}
  36. s/=2;
  37. if(subsetsum(a,n,s))cout<<"YES\n";
  38. else cout<<"NO\n";
  39. }
  40. }
Add Comment
Please, Sign In to add comment