HDU 1114 Piggy-Bank

该题利用了我们的逆向思维,同时要注意该题他的质量是一定的,也就是说背包一定要是满的,刚开始对于这类背包我们令初始值是负无穷,而这题则相反,令初始值是正无穷,每次区最小的数,同时要注意f[j-weight[i]]!=inf应为一相等就与背包一定要满的条件相矛盾;

#include<stdio.h>

#include<stdlib.h>

const int inf=0x7fffffff;

int DP( int weight[],int val[],int  N,int vol )

{

    int f[50024]={0};

    for( int i=1; i<=vol; i++ )

       f[i]=inf;

    for( int i=1; i<=N; i++ )

    {

        for( int j=0; j<=vol; j++ )

           if( weight[i]<=j&&f[j-weight[i]]!=inf&&f[j-weight[i]]+val[i]<f[j] )

                 f[j]=f[j-weight[i]]+val[i];     

    }

    return f[vol];    

}

int main()

{

    int N,n,weight[524],val[524],E,F;

    scanf( "%d",&n );

    for( int i=0; i<n;i++ )

    {

        scanf( "%d%d",&E,&F );

        scanf( "%d",&N );

        for( int j=1; j<=N; j++ )

          scanf( "%d%d",&val[j],&weight[j] );

          int t=DP( weight, val,N,F-E );

        if( t==inf )

        {

            printf( "This is impossible.\n" );    

        }

        else printf( "The minimum amount of money in the piggy-bank is %d.\n",t );     

    }

    return 0;    

}

  

你可能感兴趣的:(pig)