HDU 1171 多重背包问题,题目的链接如下,结合背包九讲理解理解。
http://acm.hdu.edu.cn/showproblem.php?pid=1171
Big Event in HDU
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 35291 Accepted Submission(s): 12240
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种物品和一个容量为V的背包。第i种物品最多有num[i]
//件可用,每件费用是c[i],价值是w[i] 背包可以不装满
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAX = 1000000;
int dp[MAX];//状态的值
int c[MAX], num[MAX]; //这里的c表示价值和体积(重量)
int v; //总体积(背包的总大小)
void zero_one_pack(int cost, int weight) // 01背包
{
for(int i = v ; i >= cost ; i--)
dp[i] = max(dp[i], dp[i-cost] + weight);
}
void complete_pack(int cost, int weight) //完全背包
{
for(int i = cost ; i <= v ; i++)
dp[i] = max(dp[i], dp[i-cost] + weight);
}
void muliple_pack(int cost, int weight, int cnt)//多重背包
{
if(cost*cnt > v){//如果总容量比这个物品的容量要小,
//那么这个物品可以直到取完,相当于完全背包
complete_pack(cost, weight);
return ;
}
else{
int k = 1;
while(k <= cnt){
zero_one_pack(k*cost, k*weight);
cnt = cnt - k;
k = 2*k;
}//背包九讲中说出,用二进制思想优化;
zero_one_pack(cnt*cost, cnt*weight);
}
}
int main()
{
int n, total;
while(cin >> n && n > 0){
v = 0;
for(int i = 0 ; i < n ; i++){
cin >> c[i] >> num[i];
v += c[i] * num[i];
}
total = v;
v /= 2;
memset(dp, 0, sizeof(dp));
for(int i = 0 ; i < n ; i++)
muliple_pack(c[i], c[i], num[i]);
cout << total - dp[v] << ' ' << dp[v] << endl;
}
return 0;
}