Getting Started 01 backpack: HDU 3466 Proud Merchants

This question is for me a bit difficult, so the reference to the two bloggers blog: bloggers a blogger 2

Problem Description
Recently, iSea went to an ancient country. For such a long time, it was the most wealthy and powerful kingdom in the world. As a result, the people in this country are still very proud even if their nation hasn’t been so wealthy any more.
The merchants were the most typical, each of them only sold exactly one item, the price was Pi, but they would refuse to make a trade with you if your money were less than Qi, and iSea evaluated every item a value Vi.
If he had M units of money, what’s the maximum value iSea could get?

Input
There are several test cases in the input.
Each test case begin with two integers N, M (1 ≤ N ≤ 500, 1 ≤ M ≤ 5000), indicating the items’ number and the initial money.
Then N lines follow, each line contains three numbers Pi, Qi and Vi (1 ≤ Pi ≤ Qi ≤ 100, 1 ≤ Vi ≤ 1000), their meaning is in the description.
The input terminates by end of file marker.

Output
For each test case, output one integer, indicating maximum value iSea could get.

Sample Input
2 10
10 15 10
5 10 5
3 10
5 10 5
3 5 6
2 7 3

Sample Output
5
11

#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
//HDU3466Proud Merchants
//这题在我看来是有点难的。首先输入的是 东西的数量和背包的容量
//其次就是输入  东西的价格,价值,和一个特别的属性
//所以需要先创建一个结构体数组
struct goods{
    int p,v,q;
}Goods[100];
//写一个比较方法,按照从小到大排序的话,cmp函数是一个自己定义的函数,返回值是bool型,它规定了什么样的关系才是“小于”,也就是排序条件
bool cmp(goods a,goods b){
    return (a.q-a.p)<(b.q-b.p);
}
int main()
{
    int f[100]={0};
    int N,M;
    int i,j;
    while(scanf("%d%d",&N,&M)!=EOF){
    for(i=0;i<N;i++)
        scanf("%d%d%d",&Goods[i].p,&Goods[i].q,&Goods[i].v);
    //然后需要对数组进行排序,需要注意的是,是按照q-p,并且是从小到大排序
    sort(Goods,Goods+N,cmp);

    //排完序之后就开始背包了
    for(i=0;i<N;i++)
        for(j=M;j>=Goods[i].q;j--)//要注意 这里是q而不是p
        f[j]=max(f[j],f[j-Goods[i].p]+Goods[i].v);

    printf("%d\n",f[M]);
    }
}




Published 72 original articles · won praise 5 · Views 2811

Guess you like

Origin blog.csdn.net/qq_41115379/article/details/104920776