HDU 2191 1171(DP,多重背包问题)

48 篇文章 0 订阅

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值