Advertisement
Oppenheimer

equal sum partition

Aug 14th, 2022
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. // check whether the given equal sum partition is possible or not.
  2. // here we dont have wt array
  3. // s1 +s2 = total sum
  4. // as s1 = s2 ====> check whether total sum/2 exists or not.
  5.  
  6. int solve(vector<int> value){
  7.     int  n = value.size();
  8.     int sum=0;
  9.     for(int a=0;a<n;a++)sum+=value[a];
  10.     if(sum%2 == 1) return 0; // as odd sum can't be partitioned into two .
  11.     vector<vector<bool>> dp (n+1 ,vector<bool>(sum+1,false));
  12.     // a represents the ath element .. b represents the knapsack present
  13.    
  14.     for(int a=0;a<=n;a++)dp[a][0] = true;// sum 0 is possible even if do not select anything
  15.    
  16.     for(int a=1;a<=n;a++){
  17.         for(int b=1;b<=sum;b++){
  18.             if(value[a-1]<=b){
  19.             dp[a][b] = dp[a-1][b-value[a-1]] || dp[a-1][b]; //either i choose the ath element or not
  20.             }else{
  21.             dp[a][b] = dp[a-1][b]; // cant choose the ath element becuase its weight is more
  22.             }
  23.         }
  24.     }
  25.     return dp[n][sum/2];
  26.  
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement