(hdu step 3.3.1)Big Event in HDU(01背包:N件物品放在容量為V的背包中,第i件物品的費用是c[i],價值是w[i]。問所能擷取的最大價值),bigevent
| Big Event in HDU |
| Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) |
| Total Submission(s): 854 Accepted Submission(s): 345 |
|
Problem DescriptionNowadays, 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).
|
InputInput 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.
|
OutputFor 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
210 120 1310 1 20 230 1-1
|
Sample Output
20 1040 40
|
| Authorlcy |
題目分析:
這是屬於背包九講中的《01 背包》。所謂的01背包,也就是說每種物品只有兩種狀態,放或者不放。這道題中,只要求出了software college所能擷取的最大價值,那麼computer college所能擷取的最大價值也就知道了。所以將software college所能擷取的最大價值sum/2設為背包的最大容量V。在這道題中,每件物品的價值w[i]同樣作為了費用c[i]。。。。只要明白以上的思路,想必編碼也就不困難了。。。
代碼如下:
/* * a.cpp * * Created on: 2015年2月12日 * Author: Administrator */#include <iostream>#include <cstdio>using namespace std;const int maxn = 5005;const int maxm = 250005;int w[maxn];//用於記錄每種物品的價值int f[maxm];//用於記錄容量為v時所能擷取的最大價值int main() {int n;while (scanf("%d", &n) != EOF, n > 0 ) {//對於n為-1時結束的處理為n>0memset(w,0,sizeof(w));//重設費用/價值為0。其實在這裡重不重設都沒有影響memset(f,0,sizeof(f));//重設儲值或能擷取的最大價值為0。這個數組一定要重設,否則可能影響狀態轉移方程f[v] = max(f[v],f[v - c[i]] + w[i]);int v, m;int sum = 0;//所有商品的總價值int i;int j;int cnt = 0;for (i = 0; i < n; ++i) {//遍曆每種物品scanf("%d%d", &v, &m);sum += v*m;//將每種物品的總價值加到所有商品的總價值中for (j = 0; j < m; ++j) {w[cnt++] = v;//記錄每一種物品的價值}}cnt -= 1;for (i = 0; i < cnt; ++i) {for (j = sum / 2; j >= w[i]; --j) {/** * 將其展開為f[i][j] = max(f[i-1][j],f[i-1][j-w[i]]+w[i])來理解 * 即:前i件物品放在容量為j的背包時所能擷取的最大價值是 * 第i-1件物品放在容量j的背包中所能獲得最大值(不放第i件物品在背包中)與 * 第i-1件物品放在容量為j-w[i]的背包中所能達到的最大值(這是騰出地方放第i件物品) * 中的最大值 */f[j] = max(f[j], f[j - w[i]] + w[i]);}}//一個學院能擷取的價值是f[sum / 2],那麼另一個能擷取的自然是sum - f[sum / 2]了printf("%d %d\n", sum - f[sum / 2], f[sum / 2]);}return 0;}