ZJU2014 Piggy-Bank - 经典动态规划

题目描述:

已知一堆硬币重量为m(<10000), 可能有n种硬币(n<500),价值和重量分别为vi,wi。要求这堆硬币的总价值至少可能是多少?若无法求出输出"This is impossible."

分析:

可以看出,此题是01背包问题的变形,即

1.每种物品有无限多

2.必须装满整个背包

就是加上这样两个限制条件的01背包。

我用的最普通的方法,感觉对物品排序的影响不大。

/*
ZJU2014 Piggy-Bank
*/

#include <stdio.h>
#include <string.h>
#define N 501
#define M 10001
#define clr(a) memset(a,0,sizeof(a))

struct nod{
    int v,w;
};
typedef struct nod node;

node a[N];
char e[M];
int b[M],maxm;
int m,n;

int cmp(void const *p,void const *q){
    node* x = (node*)p;
    node* y = (node*)q;
    if(x->w == y->w){
        return x->v - y->v >0 ? 1 : -1;
    }else return y->w - x->w;
}

int main()
{
    int i,j,k,T;
   
    scanf("%d",&T);
    while(T--)
    {
        int w1,w2;
        //init
        clr(e);
        clr(b);
       
        //input
        scanf("%d%d",&w1,&w2);
        m=w2-w1;
        scanf("%d",&n);
        for(i=0;i<n;i++)
            scanf("%d%d",&a[i].v,&a[i].w);
       
        //qsort(a,n,sizeof(a[0]),cmp);
       
        //DP
        e[0]=1;
        b[0]=0;
       
        for(i=0;i<n;i++) //each icon
        {
            for(j=0;j<=m;j++)
            {
                if(e[j]){
                    k=j+a[i].w;
                    if(k<=m&&(!e[k]||b[j]+a[i].v<b[k])){
                        b[k]=b[j]+a[i].v;
                        e[k]=1;
                    }
                }
            }
        }
       
        if(!e[m]) printf("This is impossible./n");
        else printf("The minimum amount of money in the piggy-bank is %d./n",b[m]);
       
    }
   
    //system("pause");
    return 0;
}


/*

Sample Input

3
10 110
2
1 1
30 50
10 110
2
1 1
50 30
1 6
2
10 3
20 4


Sample Output

The minimum amount of money in the piggy-bank is 60.
The minimum amount of money in the piggy-bank is 100.
This is impossible.


*/

你可能感兴趣的:(struct,ini,input,output)