用滚动数组写好像写法很简洁,但这次我试着用二维数组写Orz...还真出了好多问题..所幸最后还是AC了...
#include<stdio.h>
#include<string.h>
#include<math.h>
#define maxn 505
int p[maxn],w[maxn];
int n,m;
int dp[maxn][10005];
int min(int a,int b){
return a<b?a:b;
}
void out(){
for(int i=1;i<=n;i++){
for(int j=0;j<=m;j++){
if(dp[i][j]==0x3f3f3f3f)
printf("dp[%d,%d]=--,,",i,j);
else printf("dp[%d,%d]=%d,,",i,j,dp[i][j]);
}
printf("\n");
}
printf("\n");
}
bool solve(){
int i,j;
memset(dp,0x3f,sizeof(dp));
for(i=1;i<=n;i++){
dp[i][0]=0;
for(j=1;j<=m;j++){
dp[i][j]=dp[i-1][j];
if(j>=w[i]&&dp[i][j-w[i]]+p[i]<dp[i][j])dp[i][j]=dp[i][j-w[i]]+p[i];
}
}
//out();
if(dp[n][m]==0x3f3f3f3f)
return false;
printf("The minimum amount of money in the piggy-bank is %d.\n",dp[n][m]);
return true;
}
int main(){
freopen("t.txt","r",stdin);
int T;
scanf("%d",&T);
while(T--){
int u,v;
scanf("%d%d",&u,&v);
m=v-u;
scanf("%d",&n);
//memset(dp,0x3f,sizeof(dp));
for(int i=1;i<=n;i++)
scanf("%d%d",&p[i],&w[i]);
if(!solve())
printf("This is impossible.\n");
}
return 0;
}