jain12

partition problem solution 3

Jun 7th, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. int FindPartition(int arr[],int n){  
  5.   int total=0;
  6.   for(int i=0;i<n;i++)
  7.     total+=arr[i];
  8.   if(total%2!=0)
  9.     return 0;
  10.   total=total/2;
  11.   int sum[n+1][total+1];
  12.   for(int i=0;i<=n;i++)
  13.     sum[i][0]=1;
  14.   for(int i=0;i<=total;i++)
  15.     sum[0][i]=0;
  16.   for(int i=1;i<=n;i++){
  17.     for(int j=1;j<=total;j++){
  18.       sum[i][j]=sum[i-1][j];
  19.       if(arr[i-1]<=j)
  20.             sum[i][j]=sum[i][j]||sum[i-1][j-arr[i-1]];
  21.       }
  22.     }
  23.   return sum[n][total];
  24.   }
  25.  
  26. int main(){
  27.   int arr[] = {3,1,1,2,2,1};
  28.   int n = 6;
  29.   if (FindPartition(arr, n))
  30.         cout << "Can be divided into two subsets of equal sum";
  31.     else
  32.         cout << "Can not be divided into"
  33.              << " two subsets of equal sum";
  34.   return 0;
  35.   }
Add Comment
Please, Sign In to add comment