HDU 3466 Proud Merchants 01 knapsack problem with a restriction

HDU 3466 Proud Merchants 01 knapsack problem with a restriction

The meaning of problems

Recently, Issa went to an old country. In such a long time, it is the world's richest, most powerful kingdom. Therefore, even though their country is no longer so rich people in this country are still very proud.

Merchant is the most typical, they each sell an item, the price is PI, but they refuse to deal with you if your money is lower than the QI, ISEA VI assess the value of each project.

If he had money M units, the maximum value of Isa can have is how much?

Problem-solving ideas

p represents the required price, q represents the threshold to buy this item.

The idea is to try to buy a big qi-pi commodity, according to qi-pi descending order, but the actual encoding process needs from small to large. why? Consider when evaluated dp (i, j), dp (i, j) = max (dp (i-1, j), dp (i-1, jp [i]) + v [i]), careful analysis of the dp (i-1, jp [i]) + v [i] this case, in fact, is to find the i-th commodity bought, that is at the back to actually buy goods.

The focus here is to analyze dp (i-1, jq [i]) + v [i], Why is the first to buy the first i items? We can interpret it this way: dp (i-1, jq [i]) can be understood as the first to buy the first i items, buy the largest value of other items. I started to understand this shift difficult to understand.

#include<cstdio>
#include<algorithm>

using namespace std;

const int N=600;
const int M=6e3+7;
struct note{
    int p, limit, v;
    bool operator < (note a) const 
    {
        return limit-p < a.limit-a.p;
    }
}num[N];

int dp[M];
int main()
{
    int n, m;
    scanf("%d%d", &n, &m);
    for(int i=0; i<n; i++)
    {
        scanf("%d%d%d", &num[i].p, &num[i].limit, &num[i].v);   
    }   
    sort(num, num+n);
    for(int i=0; i<n; i++)
    for(int j=m; j>=num[i].p && j>=num[i].limit; j--)
        dp[j]=max(dp[j], dp[j-num[i].p]+num[i].v);
    printf("%d\n", dp[m]);
    return 0;   
}

Guess you like

Origin www.cnblogs.com/alking1001/p/11566999.html