题目链接:POJ 2576 Tug of War
题目
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
分析
这题其实就是求给你
n
n
n个数,从中选
k
k
k个加起来凑成一个最接近
m
m
m的值。这里可以开一个bool数组,记录能否用
j
j
j个数凑出
i
i
i,虽然
n
n
n给了100,但是我们其实遍历到
n
/
2
n/2
n/2就行了,因为限定两边差不能超过1,所以其中有一定一边是
n
/
2
n/2
n/2个数。最后只要从
n
/
2
n/2
n/2个数能凑出的数里选一个最接近
s
u
m
/
2
sum/2
sum/2的即可。
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 450*100 + 500;
bool dp[maxn][60];
int w[105];
int main()
{
int n, sm = 0;
scanf("%d", &n);
for(int i = 1; i <= n; i++) scanf("%d", &w[i]), sm += w[i];
int m = n >> 1, res = 1e9;
memset(dp, false, sizeof(dp));
dp[0][0] = true;
for(int i = 1; i <= n; i++){
for(int j = maxn-1; j >= 0; j--){
for(int k = 0; k <= m; k++){
if(dp[j][k]) dp[j+w[i]][k+1] = dp[j][k] = true;
}
}
}
for(int i = 0; i < maxn; i++)
if(dp[i][m])
if(abs(2*i-sm) < abs(2*res-sm)) res = i;
printf("%d %d\n", min(res, sm-res), max(res, sm-res));
}