POJ3466(01背包变形)

Proud Merchants

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 3805    Accepted Submission(s): 1587

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
 
题意:n件商品,每件价格pi,每件商品只有在你钱>=qi才能买入,每件价值vi。现在你有m元钱,问能购买到的商品最大价值和。
 
很好的一道题,刷完这道题对01背包和dp的后效性有了更深理解。思路就是先尝试买qi-pi大的商品,即按照qi-pi从大到小排序,但实际编码过程中需要从小到大排序。为什么呢?考虑在求dp(i, j)时,dp(i, j) = max(dp(i-1,j), dp(i-1, j-q[i]) + v[i]),仔细分析下dp(i-1, j-q[i]) + v[i] 这种情况,发现其实是先买了第i种商品,就是说排在后面的商品其实是先买的。
 
/*
ID: LinKArftc
PROG: 3466.cpp
LANG: C++
*/

#include <map>
#include <set>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <utility>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define eps 1e-8
#define randin srand((unsigned int)time(NULL))
#define input freopen("input.txt","r",stdin)
#define debug(s) cout << "s = " << s << endl;
#define outstars cout << "*************" << endl;
const double PI = acos(-1.0);
const double e = exp(1.0);
const int inf = 0x3f3f3f3f;
const int INF = 0x7fffffff;
typedef long long ll;

const int maxn = 510;
const int maxm = 5010;

struct Node {
    int cost, need, val;
} node[maxn];
int dp[maxm];
int n, m;

bool cmp(Node a, Node b) {
    return (a.need - a.cost) < (b.need - b.cost);
}

int main() {
    //input;
    while (~scanf("%d %d", &n, &m)) {
        memset(dp, 0, sizeof(dp));
        for (int i = 1; i <= n; i ++) scanf("%d %d %d", &node[i].cost, &node[i].need, &node[i].val);
        sort (node+1, node+n+1, cmp);
        for (int i = 1; i <= n; i ++) {
            for (int j = m; j >= node[i].need; j --) {
                dp[j] = max(dp[j-node[i].cost] + node[i].val, dp[j]);
            }
        }
        printf("%d
", dp[m]);
    }

    return 0;
}
原文地址:https://www.cnblogs.com/LinKArftc/p/4907462.html