Big Event in HDU
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 36662 Accepted Submission(s): 12734
Problem Description
Nowadays, we all know that Computer College is the biggest department in HDU. But, maybe you don’t know that Computer College had ever been split into Computer College and Software College in 2002.
The splitting is absolutely a big event in HDU! At the same time, it is a trouble thing too. All facilities must go halves. First, all facilities are assessed, and two facilities are thought to be same if they have the same value. It is assumed that there is N (0<N<1000) kinds of facilities (different value, different kinds).
Input
Input contains multiple test cases. Each test case starts with a number N (0 < N <= 50 – the total number of different facilities). The next N lines contain an integer V (0<V<=50 –value of facility) and an integer M (0<-M<=100 –corresponding number of the facilities) each. You can assume that all V are different.
A test case starting with a negative integer terminates input and this test case is not to be processed.
Output
For each case, print one line containing two integers A and B which denote the value of Computer College and Software College will get respectively. A and B should be as equal as possible. At the same time, you should guarantee that A is not less than B.
Sample Input
2
10 1
20 1
3
10 1
20 2
30 1
-1
Sample Output
20 10
40 40
题意:多组数据,每组数据第一行给出N,代表接着有N行数据,每行数据给出V和M,代表有M件价值为V的设备。需要尽可能平等的将这些设备分成两份,先输出稍大一点的数
思路:多重背包模板,二进制优化一下93ms水过
代码
#include <stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
//多重背包
const int maxn=50*50*50+50;
int DP[maxn];
int num[maxn];
int value[maxn];
int main()
{
int N;
while(~scanf("%d",&N)&&N>0)
{
int V=0;//背包容量的二倍
for(int i=1; i<=N; i++)
{
scanf("%d%d",&value[i],&num[i]);
V+=value[i]*num[i];
}
memset(DP,0,sizeof(DP));
for(int i=1; i<=N; i++) //遍历所有物品
{
if(num[i]*value[i]>=V/2)//这件物品相对于最大容量可以无限取用,相当于完全背包
{
for(int v=value[i]; v<=V/2; v++)
DP[v]=max(DP[v],DP[v-value[i]]+value[i]);
}
else//01背包
{
int flag=num[i];//二进制转换优化
for(int k=1; k<=flag; flag-=k,k=k*2)
for(int v=V/2; v>=value[i]*k; v--)
DP[v]=max(DP[v],DP[v-value[i]*k]+value[i]*k);
for(int v=V/2; v>=value[i]*flag; v--)
DP[v]=max(DP[v],DP[v-value[i]*flag]+value[i]*flag);
}
}
printf("%d %d\n",V-DP[V/2],DP[V/2]);
}
return 0;
}