Given n integers. Partition them into 2 sets of sums S1 and S2 such that |S1-S2| = minimum.
Code:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<set>
#include<map>
using namespace std;
int ar[1000];
int m[100000];
int main()
{
int i,j,n,k,sum=0,ans=0;
cin>>n;
for(i=0;i<n;i++) { cin>>ar[i]; sum+=ar[i];}
for(i=0; i<sum+10; i++) m[i]=0;
m[0]=1;
for(i=0; i<n; i++)
{
for(j=sum; j>=ar[i]; j--)
m[j] |= m[j-ar[i]];
}
for(i=sum/2;i>=0;i--)
if(m[i]==1)
{ans=i; break;}
cout<<(sum - 2*i)<<endl;
ans=0;
return 0;
}
Code:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<set>
#include<map>
using namespace std;
int ar[1000];
int m[100000];
int main()
{
int i,j,n,k,sum=0,ans=0;
cin>>n;
for(i=0;i<n;i++) { cin>>ar[i]; sum+=ar[i];}
for(i=0; i<sum+10; i++) m[i]=0;
m[0]=1;
for(i=0; i<n; i++)
{
for(j=sum; j>=ar[i]; j--)
m[j] |= m[j-ar[i]];
}
for(i=sum/2;i>=0;i--)
if(m[i]==1)
{ans=i; break;}
cout<<(sum - 2*i)<<endl;
ans=0;
return 0;
}
No comments:
Post a Comment