ZCMU-Tug of War
2017-01-24 21:46
369 查看
Problem D: Problem D: Tug of War
Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 42 Solved: 17
[Submit][Status][Web
Board]
Description
Problem D: Tug of War
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 weightof 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.
Input
Output
Sample Input
3100
90
20
4000
0
Sample Output
190 200【解析】
此题的意思就是给你n个人,叫你分两组,两组当中相差的人数最多只能是1,然后需要让两个组当中的人体重相差最
少,这是一场拔河比赛。我们先要把所有的体重都加起来。然后把它折合成一半,其实就是背包问题,最大体重上限
设置为体重的一半,然后人数的话,如果总人数是偶数,那人数就分成一半,否则就分成一半+1,因为是整数向下除
整。这里我们设置二维数组f[i][j],这里j代表的是体重上限,而i则是代表这个时候有多少人。其实状态转移方程
就是f[i][j]=max(f[i][j],f[i-1][j-a[i]]),其实和01背包问题是相似的。还要注意的是把小的体重先输出,再输出大
的。
#include<iostream> #include<cstring> #include<string> #include<cstdio> #include<vector> #include<algorithm> using namespace std; int f[101][22500]; int main() { int a[101]; int n,i,sum=0,m,k,p,j,q; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); sum=sum+a[i];//计算总的体重 } k=sum/2;//体重的一半 m=n; if(n%2==0) n=n/2;//算出一半有多少人 else n=n/2+1; for(i=0;i<m;i++) { for(p=1;p<=n;p++) { for(j=k;j>=a[i];j--) { f[p][j]=max(f[p][j],f[p-1][j-a[i]]+a[i]);//计算一半人最大的体重 } } } p=f [k]; q=sum-f [k]; if(p>q) swap(p,q); printf("%d %d\n",p,q); return 0; }
相关文章推荐
- Tug of War(严格限制数量的二维费用背包)
- sdut 3251 Nias and Tug-of-War 模拟
- UVA 10032(Tug of War)
- zoj 1880 - Tug of War
- 动态规划:POJ2576-Tug of War(二维费用的背包问题)
- ZOJ1880 POJ2576 Tug of War,DP
- Tug of War
- POJ 2576 Tug of War二维背包恰好装满.
- poj2576 tug of war
- Light OJ 1147 Tug of War (背包+状压)
- poj2576 Tug of War(二维费用背包)
- Tug of War
- ZOJ - 1880 Tug of War
- UVA - 10032 Tug of War (二进制标记+01背包)
- POJ2576 Tug of War (二维的01背包)
- POJ 2576 Tug of War 二维费用背包
- 第六届山东省ACM竞赛 A题 Nias and Tug-of-War(java)
- uva 10032 Problem F: Tug of War
- POJ 2576 Tug of War
- POJ 2576 Tug of War(模拟退火)