背包九讲-完全背包-HDU1114

注意的两个点就是:

题目要最后的背包价值最小,所以用min,初始化的时候把全部初始化为inf,但是f[0]=0

其次是,inf要充分大,不能是2^31-1,因为要做加法,会溢出。


#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <queue>
#include <map>
#include <set>
#include <vector>
using namespace std; 
#define inf 1147483647
int max(int a,int b)
{return a>b?a:b;} 
int min(int a,int b)
{return a<b?a:b;}
int c[505],w[505];
int f[10005];
int main()
{
 
 int t,n,m;
 cin>>t;
 while(t--)
 {
	 f[0]=0;
	 int i,j;
	 scanf("%d%d",&n,&m);
	 int big=m-n;
	 
	 	for (i=1;i<=big;i++)
		f[i]=inf;
		scanf("%d",&n);
		for (i=1;i<=n;i++)
		{
			scanf("%d%d",&w[i],&c[i]);
		}

		for (i=1;i<=n;i++)
		{
			for (j=c[i];j<=big;j++)
			{
				f[j]=min(f[j],f[j-c[i]]+w[i]);
			}
		}
		if (f[big]!=inf)
		printf("The minimum amount of money in the piggy-bank is %d.\n",f[big]);
		else
			printf("This is impossible.\n");



 }

    return 0;
}


你可能感兴趣的:(背包九讲-完全背包-HDU1114)