# Problem D: Tug of War

Problem D: Tug of War

## Problem D: Tug of War

A tug of war is to be arranged at the local office picnic. For the tug of war, the picnickers must be divided into two teams. Each person must be on one team or the other; the number of people on the two teams must not differ by more than 1; the total weight of the people on each team should be as nearly equal as possible.

The first line of input contains n the number of people at the picnic. n lines follow. The first line gives the weight of person 1; the second the weight of person 2; and so on. Each weight is an integer between 1 and 450. There are at most 100 people at the picnic.

Your output will be a single line containing 2 numbers: the total weight of the people on one team, and the total weight of the people on the other team. If these numbers differ, give the lesser first.

``````3
100
90
200
``````

``````190 200
``````

``````#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
bool f[22500][51];
int a[101], n, kk;
int i, j, k, t;
int main()
{
while (scanf("%d", &n) == 1)
{
int ss, s = 0;
for (i=1; i<=n; i++)
{
scanf("%d", &a[i]);
s += a[i];
}
ss = s/2;
if (n & 1) kk = (n>>1) + 1;
else kk = n>>1;
for (i=0; i<=ss; i++) for (j=0; j<=kk; j++) f[i][j] = false;
f[0][0] = true;
for (i=1; i<=n; i++)
for (k=min(kk, i); k>0; k--)
for (j=ss; j>=a[i]; j--)
if (f[j-a[i]][k-1]) f[j][k] = true;
while (ss)
{
if (n%2==0 && f[ss][n/2]) break;
if (n%2!=0 && f[ss][n/2+1]) break;
if (n%2!=0 && f[ss][n/2]) break;
ss--;
}
printf("%d %d\n", ss, s-ss);
}
return 0;
}
``````

``````#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdio>
using namespace std;
int n;
bool dp[101][450*101];
int weight[101];
int main()
{
while(cin>>n)
{
int i,sumweight=0;
int half,Lpeople;
bool judge[451];
bool ll[451];
memset(judge,false,sizeof(judge));
memset(dp,false,sizeof(dp));
memset(ll,false,sizeof(ll));
for(i=0 ; i<n ; ++i)
{
cin>>weight[i];
if(!judge[ weight[i] ])
judge[ weight[i] ] = true;
else ll[ weight[i] ] = true;
sumweight+=weight[i];
}
half=sumweight/2;
Lpeople=(n+1)/2;
for(i=0 ; i<n ; ++i)
{
dp[i][0]=true;
}
sort(weight,weight+n);
for(i=0 ; i<n ; ++i)
for(int people=0 ; people<Lpeople ; ++people)
for(int wei=0 ; wei+weight[i]<=half ; ++wei)
if(dp[people][wei] && !dp[people+1][ wei+weight[i] ]&&(wei!=weight[i]||ll[ weight[i] ]))
{
dp[people+1][ wei+weight[i] ]=true;
//  cout<<"dp["<<people+1<<"]["<<wei+weight[i]<<"]\n";
}
int minsum = half;
while(!dp[Lpeople][minsum])
--minsum;
int maxsum = sumweight-minsum;
cout<<min(minsum,maxsum)<<" "<<max(minsum,maxsum)<<endl;
}
return 0;
}
``````