HDU 1171 0-1背包

最近感觉DP已经完全忘了..各种爆炸,打算好好复习一发,0-1背包开始

Big Event in HDU


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

总结下,把所有的设备放到a数组里,这样就不用考虑数量问题,直接使用0-1背包就可以解决..
另外,如何保证A不小于B呢?只需要计算总数的一半最大的DP值,那就是B的值,sum-B就是A的值啦~


#include 
#include 
#include 
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define INF 0x7fffffff
//#pragma warning(disable:4996)
using namespace std;
int v[55];
int m[55];
int a[5005];
int dp[200005];
int main()
{
	//freopen("s.txt", "r", stdin);
	int n;
	while (cin >> n) {
		if (n <= 0)
			break;
		memset(dp, 0, sizeof(dp));
		memset(a, 0, sizeof(a));
		int sum = 0;
		for (int i = 0; i < n; i++) {
			cin >> v[i] >> m[i];
			sum += v[i] * m[i];
		}
		int num = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m[i]; j++) {
				a[num] = v[i];
				num++;
			}
		}
		int tmp = sum / 2;
		for (int i = 0; i < num; ++i) {
			for (int j = tmp; j >= a[i]; --j)
				dp[j] = max(dp[j], dp[j - a[i]] + a[i]);
		}
		printf("%d %d\n", sum - dp[tmp], dp[tmp]);
	}
	return 0;
}



你可能感兴趣的:(动态规划)