首页 > 其他 > 详细

【hoj】1031 背包问题

时间:2014-06-29 23:27:02      阅读:327      评论:0      收藏:0      [点我收藏+]

题目: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;
}


【hoj】1031 背包问题,布布扣,bubuko.com

【hoj】1031 背包问题

原文:http://blog.csdn.net/ymzmdx/article/details/35589583

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!