您的位置:首页 > 其它

动态规划:POJ2576-Tug of War(二维费用的背包问题)

2017-07-11 18:49 525 查看

Tug of War

Time Limit: 3000MSMemory Limit: 65536K
Total Submissions: 9236Accepted: 2572
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
Waterloo local 2000.09.30

解题心得:
1、这个题前面有一个基础题可以去看一下(魔兽争霸最后的反击),这个题只是在基础题的条件上面加了一个人数相差不超过1。这样一变就成了一个二位费用的背包问题,因为它还需要记录一下人数。
2、这个题有一些小麻烦,不注意很可能会wrong,反正我在做这道题是用的各种方法怼过去的。还是直接看代码吧。

#include<stdio.h>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn1 = 110;
const int maxn2 = 45100;
bool dp[maxn1][maxn2];
int num[maxn1];
int sum;
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
memset(dp,0,sizeof(dp));
sum = 0;
for(int i=0; i<n; i++)
{
scanf("%d",&num[i]);
sum += num[i];
}
int sum1,n1;
sum1 = sum / 2;
n1 = n / 2;
if(n % 2)
n1 += 1;//个单数的个数加1来找,不然找出的小的那一半可能会出错
if(sum % 2)
sum1 += 1;//单数的话加一个避免边界出错
dp[0][0] = true;

for(int i=0; i<n; i++)
for(int j=n1; j>=1; j--)
for(int k=sum1; k>=num[i]; k--)
{
if(dp[j-1][k-num[i]])
dp[j][k] = true;//动态规划嘛
}

int Max = 0;
for(int i=sum1; i>=0; i--)//因为在单数在前面加了1,很可能在这里找不到
{
if(dp[n1][i])
{
Max = i;
break;
}
}
if(Max == 0)//上面找不到在这里接着找
{
for(int i=sum1; i>=0; i--)
{
if(dp[n1-1][i])
{
Max = i;
break;
}
}
}

printf("%d %d\n",min(Max,sum-Max),max(Max,sum-Max));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: