Piggy-Bank 完全背包问题

http://acm.hdu.edu.cn/showproblem.php?pid=1114
完全背包求最小值
常规解法超时(没优化)

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<cmath>
#include<stdlib.h>
#include<iomanip>
#include<list>
#include<deque>
#include<map>
#include <stdio.h>
#include <queue>

#define maxn 100000+5
#define ull unsigned long long
#define ll long long
#define reP(i,n) for(i=1;i<=n;i++)
#define rep(i,n) for(i=0;i<n;i++)
#define cle(a) memset(a,0,sizeof(a))
#define mod 90001
#define PI 3.141592657

const ull inf = 1LL << 61;
const double eps=1e-5;

using namespace std;

bool cmp(int a,int b){
return a>b;
}
int val[10005],w[10005],dp[10005][10005];
int n,n1,n2,V;
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int t;
cin>>t;
while(t--)
{
cin>>n1>>n2;
V=n2-n1;
cin>>n;
for(int i=1;i<=n;i++)
scanf("%d%d",&val[i],&w[i]);

for(int i=0;i<=n;i++)
for(int j=0;j<=V;j++)
dp[i][j]=maxn;
dp[0][0]=0;val[0]=0;

for(int i=1;i<=n;i++)
for(int j=0;j<=V;j++)
for(int k=0;k*w[i]<=j;k++)
dp[i][j]=min(dp[i][j],dp[i-1][j-k*w[i]]+k*val[i]);
if(dp[n][V]!=maxn)cout<<"The minimum amount of money in the piggy-bank is "<<dp[n][V]<<"."<<endl;
else cout<<"This is impossible."<<endl;
}
return 0;
}

优化方法

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<cmath>
#include<stdlib.h>
#include<iomanip>
#include<list>
#include<deque>
#include<map>
#include <stdio.h>
#include <queue>

#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<cmath>
#include<stdlib.h>
#include<iomanip>
#include<list>
#include<deque>
#include<map>
#include <stdio.h>
#include <queue>

#define maxn 999999999
#define ull unsigned long long
#define ll long long
#define reP(i,n) for(i=1;i<=n;i++)
#define rep(i,n) for(i=0;i<n;i++)
#define cle(a) memset(a,0,sizeof(a))
#define mod 90001
#define PI 3.141592657
#define INF 999999999
const ull inf = 1LL << 61;
const double eps=1e-5;

using namespace std;

bool cmp(int a,int b){
return a>b;
}
int val[10005],vol[10005];
int dp[10005];
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int t;
int st,ed,num;
cin>>t;
while(t--)
{
cin>>st>>ed;
int V=ed-st;
cle(vol);cle(val);
cin>>num;
cle(val);cle(vol);
for(int i=1;i<=num;i++)
{
scanf("%d%d",&val[i],&vol[i]);
}
for(int i=1;i<=V;i++)
dp[i]=INF;
dp[0]=0;

for(int i=1;i<=num;i++)
for(int j=vol[i];j<=V;j++)
dp[j]=min(dp[j],dp[j-vol[i]]+val[i]);
if(dp[V]==INF)cout<<"This is impossible."<<endl;
else
cout<< "The minimum amount of money in the piggy-bank is "<<dp[V]<<"."<<endl;
}
return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值