我的代码没有通过,用了完全背包解法
#include "iostream" #include "string.h" #include "algorithm" using namespace std; struct { int p,w; }num[1000]; int minb(int a,int b){return a>b?b:a;} int main(){ int Case,a,b,weight,n,i,s,m,top,min,j,k,visit[1100],f[1100],t; cin>>Case; while(Case--){ cin>>a>>b; weight=b-a; cin>>n; for(i=1;i<=n;i++)cin>>num[i].p>>num[i].w; if(a<1||a>b){cout<<"This is impossible."<<endl;continue;} if(weight==0){cout<<"The minimum amount of money in the piggy-bank is 0."<<endl;continue;} top=n+1; for(i=1;i<=n;i++){ if(num[i].w==1){ s=1;m=weight-num[i].w; while(m>0){ num[top].p=s*num[i].p;num[top].w=s*num[i].w; top++; s=2*s; m=m-s*num[i].w; } m=m+s*num[i].w; num[i].p=m/num[i].w*num[i].p; num[i].w=m; } else{ s=2;m=weight-2*num[i].w; while(m>=0){ num[top].p=s*num[i].p;num[top].w=s*num[i].w; top++; s=2*s; m=m-s*num[i].w; } m=m+s*num[i].w; if(m>num[i].w){ num[top].p=m/num[i].w*num[i].p; num[top].w=(m/num[i].w)*num[i].w; top++; } } } //for(i=1;i<top;i++)cout<<"i.p "<<num[i].p<<" i.w "<<num[i].w<<endl; for(i=1;i<=weight;i++)f[i]=99999999; memset(visit,0,sizeof(visit)); //for(i=1;i<=weight;i++)cout<<visit[i]<<' ';cout<<endl; min=99999999;visit[0]=1; for(i=1;i<top;i++){ for(j=weight;j>=num[i].w;j--){ if(visit[j-num[i].w]){ visit[j]=1; f[j]=minb(f[j],f[j-num[i].w]+num[i].p); //cout<<j<<' '<<f[j]<<"**"<<endl;system("pause"); } } if(visit[weight]){min=minb(min,f[weight]);visit[weight]=0;f[weight]=99999999;} //cout<<i<<' ';for(j=1;j<=weight;j++)cout<<f[j]<<' ';cout<<endl; } if(min==99999999)cout<<"This is impossible."<<endl; else cout<<"The minimum amount of money in the piggy-bank is "<<min<<"."<<endl; } }
人家通过的代码,思路一对,什么都简单了,它是用了我之前有考虑到,但是没有用好,所以重新写了,重新写后,错了,嘻嘻嘻
#include<cstdio> #include<cstring> #include<algorithm> #define INF 1000000000 using namespace std; int dp[20000],P[1000],W[1000],E,F,N,M; int main(void) { int T,i,j; scanf("%d",&T); while(T--) { scanf("%d%d",&E,&F); M=F-E; scanf("%d",&N); for(i=0;i<N;i++) scanf("%d%d",&P[i],&W[i]); dp[0]=0; for(i=1;i<=M;i++) dp[i]=INF; for(i=0;i<N;i++) for(j=W[i];j<=M;j++) dp[j]=min(dp[j-W[i]]+P[i],dp[j]); if(dp[M]<INF) printf("The minimum amount of money in the piggy-bank is %d. ",dp[M]); else printf("This is impossible. "); } return 0; }