HDU3466 01背包技巧题

HDU 3466 背包

题目的意思是物品给定三个值p,q,v,p代表花费,v是价值,q是当前的钱不低于这个数才能买那个物品。 如果没有q的限制的话就完全是一道背包水题,有了q之后就变得很有趣了。
之前思考了很久,有了一点眉目,又在网上搜了很多题解看,很重要的一点,动态规划无后效性,某阶段的状态一旦确定,则此后过程的演变不再受此前各种状态及决策的影响,简单的说,就是“未来与过去无关”,当前的状态是此前历史的一个完整总结,此前的历史只能通过当前的状态去影响过程未来的演变。
那么看01背包最原始的状态转移方程 dp[i][j] = max(dp[i-1][j],dp[i-1][j-c[i]]+w[i]); 那么什么时候能转移呢,j-c[i]是花费,那么剩下的钱就是m-(j-c[i]),当m-(j-c[i]) >q[i]时能转移,整理一下有 j < m+p[i]-q[i],那么如果动态规划满足无后效性的话,则每一次更新转移的范围应该都要比前一次要小,这样才能更新时不丢失状态,所以有了一开始不知所云的按p1-q1>p2-q2排序然后背包搞起

附带一些题解给的例子:
如果一个物品是5,9,一个物品是5 6,对第一个进行背包的时候只有dp[9],dp[10],…,dp[m],再对第二个进行背包的时候,如果是普通的,应该会借用前面的dp[8],dp[7]之类的,但是现在这些值都是0,所以会导致结果出错。于是要想到只有后面要用的值前面都可以得到,那么才不会出错。
假设A,B两个物品,要使得先后顺序让所需空间最小,才能让后面的价值可能越大
假如A先放,则需要空间 q1+w2;
B先放,则所需空间为q2+w1;
假如要让A排在前面,则排序方式为 q1+w2

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<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
using namespace std;

struct Node
{
    int p;
    int q;
    int v;
}node[501];

bool cmp(Node a, Node b)
{
        return a.p-a.q > b.p-b.q;
}

int dp[10001];
int main()
{
    int n,m;
    while (scanf("%d%d",&n,&m)!=EOF)
    {
        memset(dp,0,sizeof(dp));
        for (int i = 0;i<n;i++)
                scanf("%d%d%d",&node[i].p,&node[i].q,&node[i].v);
        sort(node,node+n,cmp);

        for (int i = 0;i<n;i++)
                for (int j = m;j>=node[i].q;j--)
                dp[j] = max(dp[j],dp[j-node[i].p]+node[i].v);

        printf("%d\n",dp[m]);
    }
    return 0;
}

你可能感兴趣的:(HDU3466 01背包技巧题)