Big Event in HDU (01背包)

版权声明:转载请标明出处 https://blog.csdn.net/weixin_41190227/article/details/86534112

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

题意:给你n组数据,每组两个数,第一个表示价值,第二个表示个数,要求你分成两个部分,使得这两部分最后最接近。

解题思路:求出总和的一半,这个数值就相当于背包的容积,最后把每组数组的数都放在一个数组里,用01背包跑一边就可以了。

最后还是要告诫自己认真读题再读题,一直以为数据量是500。。 一开始以为自己用C++写,然后tle。。接着改成scanf,printf,还是tle。。。一直在tle。。。最后tle了6发,才知道数据量没搞清楚,数组大小定义小了。。。

/*
@Author: Top_Spirit
@Language: C++
*/
#include <bits/stdc++.h>
using namespace std ;
typedef unsigned long long ull ;
typedef long long ll ;
const int Maxn = 1e5 +10 ;
const ull seed = 133 ;
const int INF = 0x3f3f3f3f ;

int dp[Maxn] ;
int x, y ;
int val[Maxn] ;

int main (){
    int n ;
    while (scanf("%d", &n) && n > 0){
        memset(dp, 0, sizeof(dp)) ;
        memset(val, 0, sizeof(val)) ;
        int sum = 0 ;
        int k = 1 ;
        for (int i = 1; i <= n; i++){
            scanf("%d%d", &x, &y) ;
            sum += x * y ;
            while (y--) val[k++] = x ;
        }
//        for (int i = 0; i < k; i++) {
//            cout << val[i] << " " ;
//        }
//        cout << endl ;
        int v = sum / 2 ;
        for (int i = 1; i < k; i++){
            for (int j = v; j >= val[i]; j--){
                dp[j] = max(dp[j], dp[j - val[i]] + val[i]) ;
            }
        }
//        cout << sum - dp[v] << " " << dp[v] << endl ;
        printf("%d %d\n", sum - dp[v], dp[v]) ;
    }
    return 0 ;
}

林花谢了春红,太匆匆

无奈朝来寒雨,晚来风

猜你喜欢

转载自blog.csdn.net/weixin_41190227/article/details/86534112
今日推荐