大体题意:
给你n 种数字,每种数字的数量也是知道的,要把这些数放到A B 两个集合中,要求AB的差尽可能少,并且 A不少于B?
思路:
差值最少是0,显然是所有数字之和sum/2 这样肯定是最优,所以题目转换成了 在体积不超过sum/2的情况下 尽可能挑更多的数字,使得重量尽可能大,重量也等于体积!
这不就是01背包了吗!
这个题 错了n 次, 输入 负数结束 而不是-1 = = !
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 300000 + 1;
int dp[maxn];
int a[maxn];
int main(){
int n;
while(scanf("%d",&n) == 1 && n > 0){
int cnt = 0;
int sum = 0;
memset(dp,0,sizeof dp);
for (int i = 0; i < n; ++i){
int u,v;
scanf("%d %d",&u, &v);
for (int k = 0; k < v; ++k){
a[++cnt] = u;
sum += u;
}
}
for (int i = 1; i <= cnt; ++i){
for (int j = a[i]; j <= sum/2; ++j){
dp[j] = max(dp[j],dp[j-a[i]] + a[i]);
}
}
printf("%d %d\n",sum-dp[sum/2],dp[sum/2]);
}
return 0;
}
Big Event in HDU
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 36510 Accepted Submission(s): 12680
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).
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.
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
Author
lcy
Recommend