本文主要是介绍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;
}
这篇关于Piggy-Bank 完全背包问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!