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
题意: 两队人进行拔河,现在要写一个程序找到两队人的总体重分配如何分配才会使得两队的体重差最小,找到之后输出两队的总重量,小的先输出。
题解: 背包思想。用一个二维数组来表示状态
d
p
[
i
]
[
j
]
:
表
示
选
前
i
个
人
时
总
重
量
能
否
达
到
j
dp[i][j]:表示选前 i 个人时总重量能否达到 j
dp[i][j]:表示选前i个人时总重量能否达到j。
如果选择前i个人能够恰好达到重量 j 时,将dp[i][j] 置为 1,否则将dp[i][j]置为0。我们将所有的状态都放到dp数组中之后再从所有人的总重量的中间值开始筛选,如果此时
d
p
[
(
n
+
1
)
/
2
]
[
(
s
u
m
+
1
)
/
2
]
dp[(n+1)/2][(sum+1)/2]
dp[(n+1)/2][(sum+1)/2] 为 1 则说明刚好能够将所有人平均分组,否则继续向下一个重量进行筛选(dp数组的第二维度逐步加一或者逐步减一)直至筛选至
d
p
[
(
n
+
1
)
/
2
]
[
m
]
dp[(n+1)/2][m]
dp[(n+1)/2][m] 为一时,这时选出的答案即使得两组总重量差最小的结果,然后用总重量减去这一重量,另外一半就是另外一组的重量。
解释一下为什么结果中只选取到
d
p
[
(
n
+
1
)
/
2
]
dp[(n+1)/2]
dp[(n+1)/2] 。我们是要把所有人分成两队,所以我们只要从里面选出一半的人构成一队,那么剩下的人就是外一队。所以在dp数组中我们只要留出(n+1)/ 2 个人的坑位就行,然后从总人数中选出一半的人填到这些坑位中。
c++ AC 代码
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int n, sum = 0;
int a[500];
int dp[110][110 * 500];
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%d", a + i);
sum += a[i]; // 所有人的总重量
}
for (int i = 0; i <= (n + 1) / 2; i++) // 一个人都不选的时候重量为0,这个状态明显存在
dp[i][0] = 1;
for (int i = 1; i <= n; i++) // 遍历所有人员
for (int j = 1; j <= (n + 1) / 2; j++) // 填 (n+1)/2 个坑位
for (int k = 0; k <= (sum + 1) / 2; k++) // 选出的这些人能够构成的重量(即背包体积)
if (k >= a[i] && dp[j - 1][k - a[i]]) //
dp[j][k] = 1;
int ans = (sum + 1) / 2;
while (!dp[(n + 1) / 2][ans]) // 找出两队差距最小的那个重量
ans--;
int ansmin = sum - ans;
if (ansmin > ans) // 如果ansmin的值比ans的值大,交换它两的值
swap(ansmin, ans);
printf("%d %d\n", ansmin, ans);
return 0;
}