POJ 2576 二维背包
Tug of War
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 8437 | Accepted: 2292 |
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
题目意思:
一个组有n个人,现在需要把这n个人分成两组,两组的人数的个数相差不超过1,并且使得二组的人的体重之和相差尽可能小;
解题思路:
二位背包,nn=(n+1)>>1,sum=sum_weight>>1;在此基础上进行背包;
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<ctime> 5 #include<algorithm> 6 #include <map> 7 #include <queue> 8 using namespace std; 9 const int maxn=57; 10 const int maxs=20500; 11 bool dp[maxn][maxs]; 12 int weight[107]; 13 int n; 14 int sum; 15 int slove() 16 { 17 memset(dp,0,sizeof(dp)); 18 dp[0][0]=1; 19 int ans=0; 20 int nn=(n+1)>>1; 21 int sum2=sum>>1; 22 for(int k=1;k<=n;k++) 23 for(int i=nn;i>=1;i--) 24 for(int j=sum2;j>=weight[k];j--) 25 26 { 27 if(!dp[i][j]) dp[i][j]=dp[i-1][j-weight[k]]; 28 if(dp[i][j]&&j>ans) ans=j; 29 } 30 31 return ans; 32 } 33 int main() 34 { 35 while(~scanf("%d",&n)){ 36 sum=0; 37 for(int i=1;i<=n;i++) 38 { 39 scanf("%d",&weight[i]); 40 sum+=weight[i]; 41 } 42 int ans=slove(); 43 int ans2=sum-ans; 44 if(ans>ans2) swap(ans,ans2); 45 printf("%d %d\n",ans,ans2); 46 } 47 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步