背包,初始化成无穷大/小,可以记录路径。
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int c[10100],v[10100],dp[10100],n;
int INF=0x3f3f3f3f;
int main()
{
int i,uuu,lll,T;
scanf ("%d",&T);
while(T--)
{
scanf("%d%d",&uuu,&lll);
int V=lll-uuu;
scanf ("%d",&n);
for(int i=0; i<n; i++)
scanf("%d%d",&v[i],&c[i]);
for (int i=0;i<=V;i++) dp[i]=INF;
dp[0]=0;
for(int i=0; i<n; i++)
{
for(int j=c[i]; j<=V; j++)
{
if(dp[j-c[i]]<INF)
dp[j]=min(dp[j],dp[j-c[i]]+v[i]);
}
}
if (dp[V]>=INF) printf ("This is impossible.\n");
else printf("The minimum amount of money in the piggy-bank is %d.\n",dp[V]);
}
return 0;
}