当前位置: 代码迷 >> 综合 >> HDU--dp练习--1009--Big Event in HDU
  详细解决方案

HDU--dp练习--1009--Big Event in HDU

热度:29   发布时间:2024-01-12 14:33:28.0

题目:

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.<br>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&lt;N&lt;1000) kinds of facilities (different value, different kinds).<br>

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.<br>A test case starting with a negative integer terminates input and this test case is not to be processed.<br>

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.<br>

Sample Input
  
   
2 10 1 20 1 3 10 1 20 2 30 1 -1

Sample Output
  
   
20 10 40 40
题目大意:

分东西给两个学院,给出东西的价值和件数,使得所分得的价值尽可能相等,输出平分后各学院得到的价值。

第一个价值要大于等于第二个价值。

解题思路:

01背包问题。

状态转移方程:dp[k] = max(dp[k], dp[k-v[i]]+v[i]);

源代码:

#include <bits/stdc++.h>
using namespace std;
int  dp[100005];
int main()
{
    int n,v[55],m[55],i,j;
    while(cin >> n)
    {
        if(n < 0)
            break;
        int sum = 0;
        for(i = 0; i < n; i++)
        {
            cin >> v[i] >> m[i];
            sum += v[i] * m[i];
        }
        
        int sum1 = sum / 2;  
//尽可能均分
        memset(dp,0,sizeof(dp));
        for(i = 0; i < n; i++)
        {
            for(j = 0; j < m[i]; j++)
                for(int k = sum1; k >= v[i]; k--)
                {
                    dp[k] = max(dp[k], dp[k-v[i]]+v[i]);
                }
        }
        
        cout << sum - dp[sum1] << " " << dp[sum1] << endl;
    }
    return 0;
}

  相关解决方案