原题:
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
-1Sample Output
20 10
40 40
背包问题详细讲解可参考:
http://blog.csdn.net/na_beginning/article/details/62884939(01背包,完全背包,多重背包)
http://blog.csdn.net/hcwzq/article/details/6661204
此题的另一种解法:http://www.cnblogs.com/kuangbin/archive/2013/04/15/3022741.html(混合背包)
此题的另一种解法:http://blog.csdn.net/IAccepted/article/details/24651887(母函数)
此题的另一种解法:http://blog.csdn.net/hdd871532887/article/details/41287857(多重背包 + 母函数)
题意:
有N样物品,每样物品价值是V,件数是M。尽量把这些物品分成两堆使得两边总价值最接近。输出分得的两堆各自的价值。
代码:
/**
* 动态规划【非递归】
* 此题为多重背包,可看做是01背包问题
*/
#include<stdio.h>
#include <algorithm>
using namespace std;
int V[5001];//50*100种物品的价值
int dp[125001];//背包假设的最大容量50*100*50/2=125000
int AllValue;//总值
//参数:物品种类个数(kind-1)
void ZeroOnePack(int kind)
{
int i, j;
for (i = 0; i < kind; i++)//遍历每一种物体
{
//背包最大容量为AllValue/2
for (j = AllValue/2; j >= V[i]; j--)
//通过遍历每一种物体,不断更新不同容量j的背包能存放的最大价值
//遍历在不同容量j(AllValue/2<=j<=V[i])的背包下,背包最多能放置多少价值
{
dp[j] = max(dp[j], dp[j - V[i]] + V[i]);
//在容量为j的背包下,选择是否将物体i(价值为V[i])放置到背包中
//1.不放:取原来容量为j的背包的价值
//2.放:取容量为j-V[i]的背包的价值+物体i的价值
}
}
}
int main()
{
short N, i, v, m;
int kind;
while (scanf("%d",&N) && N > 0)
{
memset(V, 0, sizeof(V));
memset(dp, 0, sizeof(dp));
AllValue = 0;
kind = 0;
for (i = 0; i < N; i++)
{
scanf("%d%d", &v, &m);
while (m--)//将多重背包看作01背包(如:10个A看作是10个不同的A但是有相同的价值V)
{
V[kind++] = v;//每一种物品的价值
AllValue += v;//总价值
}
}
ZeroOnePack(kind);
printf("%d %d\n", AllValue - dp[AllValue / 2], dp[AllValue / 2]);
}
}