首页 > 代码库 > 【hoj】1031 背包问题

【hoj】1031 背包问题

题目:http://acm.hit.edu.cn/hoj/problem/view?id=1031

刚学完算法,但是一直都只停留在ppt以及伪代码层次,都没有实际的编过程序,所以一遇到这个题就傻了,用了贪心,但是有些情况求得的不是最优解,用动态规划才能考虑到所有情况找到最优解

#include <iostream>
#include <cstdio>
#define MAX 510
#define MAXH 10010

using namespace std;

int min(int a,int b)
{
    if(a > b)
        return b;
    else
        return a;
}
int main()
{
    int e,f,n,t;
    int weight;
    int p[MAX],w[MAX],g[MAXH];
    cin>>t;
    while(t--){
        cin>>e>>f;
        weight = f-e;
        cin>>n;
        for(int i = 1;i <= n;i++)
             cin>>p[i]>>w[i];
        g[0] = 0;
        for(int i = 1;i <= weight;i++)
            g[i] = 999999;
        for(int i = 1;i <= n;i++)
            for(int j = w[i];j <= weight;j++)
                g[j] = min(g[j],g[j-w[i]]+p[i]);
        if(g[weight] == 999999)
            cout<<"This is impossible."<<endl;
        else
            cout<<"The minimum amount of money in the piggy-bank is "<<g[weight]<<'.'<<endl;
    }
    return 0;
}