HDU-1171 Big Event in HDU(多变的01背包解多重背包)

Big Event in HDU

题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1171

Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

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

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 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个物品,接下来是每个物品的价值和数量,让我们将其分成两份,且两个的价值要尽可能的接近。
emmm。。。很简单的一道题,但是我还是
HDU-1171 Big Event in HDU(多变的01背包解多重背包)_第1张图片
刚开始RE是因为我将数组开太小了,dp的数组应该是50 * 50* 100的大小,而我忽略了它的价值,只开了50*100,后来RE后我又开大了十倍,还是RE,最后翻了一下别人的代码才发现要开到50 *50 *100,接下来就是题目了,有点毒瘤,明明说了以负数结尾,结果还要用!EOF否则就TLE了,然后我没有认真看题,就以为是-1为结尾,WA了好几发。。。
好了,题目要使他们尽可能的接近,我们首先能想到的就是直接将总价值/2 就好了,没有毛病,我们将sum/2设为上限,然后开始挑选,使其尽可能接近sum/2,那么这个方程也就出来了,dp[j]=max(dp[j],dp[j-a[i]]+a[i]);而后我们所要的dp[sum/2]就是一个答案,sum-dp[sum/2]就是另一个答案了。当然,有一个麻烦就是这些物品的数量,不过我们可以将其直接转化为一个一个的:

for (int i=1; i<=n; i++) {
	scanf ("%d%d",&m,&num);
	for (int j=1; j<=num; j++) {
		a[++tot]=m;
		sum+=m;
	}
}

这样的话这道题就变成了标准的01背包的题目了,就可以直接过了:

#include 
#include 
#include 
using namespace std;
int dp[500500],a[5002];
int max(int a,int b)
{
	return a>b?a:b;
}
int main()
{
	int n,num,m;
	while (~scanf ("%d",&n)){
		if (n<=0) break;
		int tot=0,sum=0;
		memset(a,0,sizeof(a));
		memset(dp,0,sizeof(dp));
		for (int i=1; i<=n; i++){
			scanf ("%d%d",&m,&num);
			for (int j=1; j<=num; j++){
				a[++tot]=m;
				sum+=m;
			}
		}
		int k=sum/2;
		for (int i=1; i<=tot; i++){
			for (int j=k; j>=a[i]; j--){
				dp[j]=max(dp[j],dp[j-a[i]]+a[i]);
			}
		}
		int A=dp[k],B=sum-dp[k];
		printf ("%d %d\n",B,A); //这里的B一定会大于等于A,想想01背包的性质就知道了
	}	
	return 0;
}

你可能感兴趣的:(#,一般线性DP)