HDU 2191——珍惜现在,感恩生活
这道题是多重背包问题的模板,代码如下:
#include<iostream>
using namespace std;
int cost[500];
int w[500];
int dp[100];
int main(){
// freopen("data.txt","r",stdin);
ios::sync_with_stdio(false);
int C;
cin>>C;
while(C--){
int n,m;
cin>>n>>m;
int tot=0;
for(int i=0;i<m;++i){
int p,h,c;
cin>>p>>h>>c;
int t=1;
while(t*2<=c){
cost[tot]=p*t;
w[tot]=h*t;
tot++;
t*=2;
}
t=c-t+1;
cost[tot]=p*t;
w[tot++]=h*t;
}
for(int i=0;i<=n;++i){
dp[i]=0;
}
for(int i=0;i<tot;++i){
for(int j=n;j>=0;--j){
if(j-cost[i]<0)break;
dp[j]=max(dp[j],dp[j-cost[i]]+w[i]);
}
}
cout<<dp[n]<<endl;
}
return 0;
}
HDU 1171 Big Event in HDU
这道题其实不难,但是一直错,然后找了好长时间原因。后来发现题目中说的输入中断的条件是最后一个n为负数,但是我一直拿以-1中断写的。太马虎了。
代码如下:
#include<iostream>
#include<cstring>
using namespace std;
int value[500];
int num[550];
int dp[300000];
int main(){
// freopen("data.txt","r",stdin);
ios::sync_with_stdio(false);
int n;
while(cin>>n){
if(n<=-1)break;
int tot=0;
int cnt=0;
for(int i=0;i<n;++i){
int v,t;
cin>>v>>t;
if(t==0)continue;
tot+=v*t;
int p=1;
value[cnt]=v*p;
num[cnt++]=p;
t-=p;
p*=2;
while(p<=t){
value[cnt]=v*p;
num[cnt++]=p;
t-=p;
p*=2;
}
if(t){
value[cnt]=v*t;
num[cnt++]=t;
}
}
int tt=tot;
tot/=2;
memset(dp,0,sizeof(dp));
for(int i=0;i<cnt;++i){
for(int j=tot;j>=0;--j){
if(j<value[i])break;
dp[j]=max(dp[j-value[i]]+value[i],dp[j]);
}
}
int a,b=0;
b=dp[tot];
a=tt-b;
cout<<a<<' '<<b<<endl;
}
return 0;
}
在网上看到了别人的解题方法,他把物品的数量的拆分放在了求dp的循环中,这样可以把空间复杂度降低。
此人的博客地址:http://happylch21.blog.163.com/blog/static/16563975920107177583052/