Tug of War
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 8892 | Accepted: 2463 |
Description
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.
Input
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.
Output
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.
Sample Input
3 100 90 200
Sample Output
190 200
Source
题意:有n个数,将这n个数分成两份,这两份的数量相差不能超过1,总和要尽可能相等,要求每个数都要选到
考虑动规的思想,f[i][j]表示选i个人,能否使总和到达j
显然,讨论到第s个人的时候,如果f[i][j]=1,那么f[i+1][j+value[s]]=1
这里对i和j都是有限制的,i<=(n+1)/2,j<=sum/2
这里有一个小细节,如果把i的范围换成i<=n/2是不行的,想一想为什么
#include<cstdio>
#include<iostream>
using namespace std;
const int maxn=105,inf=1e9,maxm=455;
inline void _read(int &x){
char t=getchar();bool sign=true;
while(t<'0'||t>'9')
{if(t=='-')sign=false;t=getchar();}
for(x=0;t>='0'&&t<='9';t=getchar())x=x*10+t-'0';
if(!sign)x=-x;
}
int n,s[maxn];
bool f[maxn][maxn*maxm];
int main(){
int i,j,halfm,halfn,sum=0,k,ans;
cin>>n;
for(i=1;i<=n;i++){
cin>>s[i];
sum+=s[i];
}
halfm=sum/2;
halfn=(n+1)/2;
for(i=0;i<=halfn;i++)f[i][0]=1;//初始化
for(i=1;i<=n;i++)
for(j=0;j<=halfn;j++)
for(k=0;k+s[i]<=halfm;k++)
if(f[j][k])
f[j+1][k+s[i]]=1;
ans=halfm;
while(!f[halfn][ans])ans--;
int anss=sum-ans;
if(anss>ans)swap(anss,ans);
cout<<anss<<" "<<ans;
}