hdu 1114 完全背包

完全背包化为多重背包,时间为:250ms

#include<iostream> #include<cstdio> #include<cmath> using namespace std; int num[500]; int w[500],p[500]; int n; int dp[10000]; int min(int a,int b) { return a>b?b:a; } void solve(int sum,int weight,int value) { for(int i=sum;i>=weight;i--) dp[i]=min(dp[i],dp[i-weight]+value); } int main() { int t; scanf("%d",&t); while(t--) { int e,f,m; scanf("%d%d",&e,&f); m=f-e; int i,k; scanf("%d",&n); for(i=0;i<n;i++) scanf("%d%d",&p[i],&w[i]); for(i=0;i<=m;i++) dp[i]=100000000; dp[0]=0; for(i=0;i<n;i++) num[i]=(int)ceil(double(m)/(double)w[i]); for(i=0;i<n;i++) { k=1; while(k<num[i]) { solve(m,k*w[i],k*p[i]); num[i]-=k; k<<=1; } solve(m,k*w[i],k*p[i]); } if(dp[m]!=100000000) printf("The minimum amount of money in the piggy-bank is %d./n",dp[m]); else printf("This is impossible./n"); } return 0; }  

 

用完全背包做:109ms,神啊...

#include<iostream> #include<cstdio> #include<cmath> using namespace std; int num[500]; int w[500],p[500]; int n; int dp[10000]; int min(int a,int b) { return a>b?b:a; } void solve(int sum,int weight,int value) { for(int i=weight;i<=sum;i++) dp[i]=min(dp[i],dp[i-weight]+value); } int main() { int t; scanf("%d",&t); while(t--) { int e,f,m; scanf("%d%d",&e,&f); m=f-e; int i,k; scanf("%d",&n); for(i=0;i<n;i++) scanf("%d%d",&p[i],&w[i]); for(i=0;i<=m;i++) dp[i]=100000000; dp[0]=0; for(i=0;i<n;i++) num[i]=(int)ceil(double(m)/(double)w[i]); for(i=0;i<n;i++) solve(m,w[i],p[i]); if(dp[m]!=100000000) printf("The minimum amount of money in the piggy-bank is %d./n",dp[m]); else printf("This is impossible./n"); } return 0; }  

你可能感兴趣的:(ini)