J - Big Event in HDU
题干
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
题解
并不能过的背包,只提供思路。
结果不能过是因为结束符是负数,而不一定是-1,我佛了。
并不是分组背包,因为每种价值的设施都可以拿任意多个,所以本质上还是组内的0-1背包,只不过需要把价值和个数展开 30 3 看做 30 30 30,一组中取几个的问题
dp[sum/2]相当于用背包一半的容量能够得到的最大价值,由于分成两半相对于总价值是互补的,所以如此一定能得到最靠近的两半价值
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int val[1005],cnt[1005],dp[5000005];
int main()
{
int n;
while(cin>>n){
if(n < 0) break;
memset(dp,0,sizeof(dp));
int sum = 0;
for(int i = 0 ; i < n ; ++i){
scanf("%d%d",val+i,cnt+i);
sum += val[i] * cnt[i];
}
int m = sum / 2;
//枚举设施
for(int i = 0 ; i < n ; ++i){
//枚举设施个数(结合下层枚举循环展开组内设施)
for(int j = 1 ; j <= cnt[i] ; ++j){
//枚举背包容量
for(int k = m ; k >= j * val[i] ; --k){
dp[k] = max(dp[k],dp[k - j * val[i]] + j * val[i]);
}
}
}
printf("%d %d\n",sum - dp[m],dp[m]);
}
return 0;
}
/*
给定N种设施(每种设施拥有不同的价值)
价值 设施个数
尽量将设施分成两组,使得价值相近,输出时先输出较大的
*/
总之展开是展开组内设施,那么做二维其实也行
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int val[100005],dp[5000005];
ll sum,half;
int main()
{
int n;
while(cin>>n){
if(n < 0) break;
memset(dp,0,sizeof(dp));
sum = 0;
int index = 0;
for(int i = 0 ; i < n ; ++i){
int v,c;
cin>>v>>c;
sum += v * c;
while(c--) val[index++] = v;
}
half = sum / 2;
n = index;
for(int i = 0 ; i < n ; ++i){
for(int j = half ; j >= val[i] ; --j){
dp[j] = max(dp[j],dp[j - val[i]] + val[i]);
}
}
cout<<sum - dp[half]<<' '<<dp[half]<<endl;
}
return 0;
}