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).
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).
A test case starting with a negative integer terminates input and this test case is not to be processed.
2 10 1 20 1 3 10 1 20 2 30 1 -1
20 10 40 40
这道题就是说怎样才能分的更均匀,所以我们只需要把sum/2,尽量把这个包装满。然后总额减去这个背包,就是另一个背包的容量
将 同种的多个物品,看作多种物品,这样的话,就可以转换为01背包
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=2.5e5;
int dp[maxn];
int val[52];
int num[52];
int main()
{
int n;
while(~scanf("%d",&n))
{
if(n<0) break;
memset(val,0,sizeof(val));
memset(num,0,sizeof(num));
memset(dp,0,sizeof(dp));
int sum=0;
for(int i=1;i<=n;i++)
{
scanf("%d %d",&val[i],&num[i]);
sum += num[i]*val[i];
}
int half=sum/2;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=num[i];j++)
{
for(int m=half;m>=val[i];m--)
dp[m]=max(dp[m],dp[m-val[i]]+val[i]);
}
}
printf("%d %d\n",sum-dp[half],dp[half]);
}
return 0;
}
二进制的转换,速度更快
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=2.5e5;
int dp[maxn];
int val[400];
int main()
{
int n;
while(~scanf("%d",&n))
{
if(n<0) break;
memset(val,0,sizeof(val));
memset(dp,0,sizeof(dp));
int sum=0;
int cnt=1;
for(int i=1;i<=n;i++)
{
int w,num;
scanf("%d %d",&w,&num);
sum += w*num;
int k=1;
while(num-k>=0)
{
num-=k;
val[cnt++]=k*w;
k*=2;
}
if(num)
val[cnt++]=num*w;
}
int half=sum/2;
for(int i=1;i<cnt;i++)
{
for(int m=half;m>=val[i];m--)
dp[m]=max(dp[m],dp[m-val[i]]+val[i]);
}
printf("%d %d\n",sum-dp[half],dp[half]);
}
return 0;
}