Proud Merchants

Proud Merchants
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 3557 Accepted Submission(s): 1479

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

Author
iSea @ WHU

Source
2010 ACM-ICPC Multi-University Training Contest(3)——Host by WHU
按照q-p的大小进行排序,再进行01背包,至于为什么这样排序,网上的题解没有看懂,在我看来,普通的01背包每次的状态转移都是基于前一个状态,所以只有尽量减少状态的损失才可以得到最优解,而状态损失量就q-p

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <algorithm>

using namespace std;

typedef long long LL;

typedef pair<int,int>p;

const int INF = 0x3f3f3f3f;

struct node
{
    int p;
    int q;
    int v;
    int dis;
}Th[550];

int Dp[5010];

int n,m;

bool cmp(node a,node b)
{
    return a.dis<b.dis;
}
int main()
{
    while(~scanf("%d %d",&n,&m))
    {
        for(int i=0;i<n;i++)
        {
            scanf("%d %d %d",&Th[i].p,&Th[i].q,&Th[i].v);
            Th[i].dis=Th[i].q-Th[i].p;
        }

        memset(Dp,0,sizeof(Dp));

        sort(Th,Th+n,cmp);

        for(int i=0;i<n;i++)
        {
            for(int j=m;j>=Th[i].q;j--)
            {
                Dp[j]=max(Dp[j],Dp[j-Th[i].p]+Th[i].v);
            }
        }
        printf("%d
",Dp[m]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/juechen/p/5255973.html