ACM刷題之路(二十二)多重揹包轉01揹包 HDU 1171

題目鏈接:傳送門

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

題意:

樣例:

2

10 1

20 1

意思是兩種物品,質量爲10的物品有一個,質量爲20的物品有一個,求如何分使得最大程度的兩等分

答案當然是  : 20   10   (題目規定大的放前面)

3

10 1

20 2

30 1 

意思是三種物品,質量爲10的物品有一個,質量爲20的物品有兩個,,質量爲30的物品有一個,求如何分使得最大程度的兩等分

答案當然是  : 40   40  即20 20放一起   、10 30 放一起即可 

分析:本題我採用多重揹包轉01揹包的做法,把輸入的物品質量放入a數組,如果物品數量大於1,就放多次,當然可以二進制優化,但在本題中不優化也可以AC。

另外注意判斷輸入結束必須是t<0 ,而不是t==-1!!!

另外注意判斷輸入結束必須是t<0 ,而不是t==-1!!!

另外注意判斷輸入結束必須是t<0 ,而不是t==-1!!!

當然下面就是01揹包的模板

for i=1..N
    for v=V..0
        f[v]=max{f[v],f[v-c[i]]+w[i]};

在本題中,第一層遍歷物品的個數N,第二層遍歷揹包容量sum/2,狀態轉移方程一套就可以了。

注意dp數組的初始化,還有輸出大的放前面即可。

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int a[5002];
int dp[500002];
int maxx(int x, int y) {
	return x > y ? x : y;
}
int main()
{
	int t;
	while (~scanf_s("%d", &t) && t >= 0) {
		int len = 0;
		int sum = 0;
		while (t--) {
			int x, y;
			scanf_s("%d%d", &x, &y);
			sum += x * y;
			while (y--) {
				a[len++] = x;
			}
		}
		int summ = sum;
		sum /= 2;
		memset(dp, 0, sizeof(dp));
		for (int i = 0; i < len; i++) {
			for (int j = sum; j >= a[i]; j--) {
				dp[j] = maxx(dp[j], dp[j - a[i]] + a[i]);
			}
		}
		printf("%d %d\n", summ - dp[sum], dp[sum]);
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章