POJ 1578 Tug of War|背包问题|动态规划

问题描述

总时间限制: 3000ms 内存限制: 65536kB

描述

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

题目解决

拔河要求两边人数不能相差大于一,两边的重量要尽可能接近。

动态规划,首先的想法是背包问题,使用一个矩阵dp[i][j],i表示个数,j表示达到的重量

然后如果每次都是正着做,会导致一个值反复加很多遍,所以每次遍历要反着做

#include
#include
#include
using namespace std;int dp[120][45010];
int arr[120];
int main()
{int n;while(~scanf("%d",&n)){int sum=0;for(int i=0;i=arr[i];j--)for(int k=half;k>0;k--)if(dp[k-1][j-arr[i]])dp[k][j]=1;for(int i=mid;i>=0;i--)if(dp[half][i]||dp[half-1][i]){printf("%d %d\n",i,sum-i);break;}}return 0;
}

打印了一下中间过程

		for(int i=0;i<=half;i++){for(int j=0;j<=mid;j++){printf("%d ",dp[i][j]);}printf("\n");}

3 10 9 21
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 
19 21


5 1 2 3 4 5
1 0 0 0 0 0 0 0 
0 1 1 1 1 1 0 0 
0 0 0 1 1 1 1 1 
0 0 0 0 0 0 1 1 
7 8


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部