Problem S
Time Limit : 10000/5000ms (Java/Other) Memory Limit :65536/32768K (Java/Other)
Problem Description
Nowadays, we allknow that Computer College is the biggest department in HDU. But, maybe youdon't know that Computer College had ever been split into Computer College andSoftware College in 2002.<br>The splitting is absolutely a big event inHDU! At the same time, it is a trouble thing too. All facilities must gohalves. First, all facilities are assessed, and two facilities are thought tobe same if they have the same value. It is assumed that there is N(0<N<1000) kinds of facilities (different value, differentkinds).<br>
Input
Input containsmultiple test cases. Each test case starts with a number N (0 < N <= 50-- the total number of different facilities). The next N lines contain aninteger 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 aredifferent.<br>A test case starting with a negative integer terminatesinput and this test case is not to be processed.<br>
Output
For each case,print one line containing two integers A and B which denote the value ofComputer College and Software College will get respectively. A and B should beas equal as possible. At the same time, you should guarantee that A is not lessthan B.<br>
Sample Input
2
10 1
20 1
3
10 1
20 2
30 1
-1
Sample Output
20 10
40 40
题意:求把总价值分为两个数,使这两个数接近相等,而且这两个数必须由所有设备中的其中几种设备价值构成,并先输出比较大的数,再输出另一个数。
解题思路:DP算法,背包问题,求法是先求出总价值sum,再用dp[]求sum/2最多能放多少价值!即可以求出其中一个数了,另一个就是sum-dp[sum/2]了。
状态:f[j]:表示软件学院取得容量为j时能获得的最大值,j<=sum/2;
状态转移:f[j]=max{f[j],f[j-v[i]]+v[i]}
注意数组的大小(0<n<=50,0<v<=50,0<m<=100)
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define MAX 300000
int dp[MAX],v[1000],m[1000];
int main()
{
int i,j,n,k;
while(cin>>n&&n>=0)
{
int sum=0;
for(i=0;i<n;i++)
{
cin>>v[i]>>m[i];
sum+=v[i]*m[i];
}
memset(dp,0,sizeof(dp));
for(i=0;i<n;i++)
for(j=1;j<=m[i];j++)
for(k=sum/2;k>=v[i]*j;k--)
if(dp[k]<dp[k-v[i]]+v[i])
dp[k]=dp[k-v[i]]+v[i];
if(sum-dp[sum/2]>dp[sum/2])
cout<<sum-dp[sum/2]<<" "<<dp[sum/2]<<endl;
else cout<<dp[sum/2]<<" "<<sum-dp[sum/2]<<endl;
}
return 0;
}