HDU 3466 - Proud Merchants

Title Description

Proud Merchants

Solution: sequencing + 0-1 knapsack problem

First explain how to deal with the lowest transaction price Q i Q_i The problem:

Example. 1
. 3 10
. 5 10. 5 (Commodity A)
. 3. 5. 6 (Commodity B)
2. 7. 3

If we buy merchandise to buy A B goods, the total value is 11; if the first buy goods B, then the next time will not be able to buy top grade of A, the description lowest trading prices mainly reflected on the issue of the purchase order.

Suppose product A, B, the corresponding figures were P a , Q a P_a, Q_a with P b , Q b P_b, Q_b If the first to buy A buy B, then at least need P a + Q b P_a+Q_b Money; if you at least need to turn P b + Q a P_b+Q_a Money. Let us assume that at this time of the purchase order first and then A B so spend the least money, then there is inequality P a + Q b > P b + Q a P_a+Q_b > P_b+Q_a , which is P a Q a > P b Q b P_a-Q_a>P_b-Q_b So it says P Q and Q large commodity should give priority to buy, so we follow P Q and Q value of a commodity prior to ordering.

Then we think about a problem: P Q and Q large goods to buy, then it should be sorted according to P Q and Q values from small to large, from large to small or do? 0-1 knapsack problem is the reverse enumeration, when it should be sorted in ascending order, thus ensuring P Q and Q large commodity to purchase

Finally, j j loop inside, we should j > = v o l u m e [ i ] j>=volume[i] to j = c o m [ i ] . Q j=com[i].Q , because it not only meets the minimum trading price also meet plenty of money to buy items

#include <iostream>
#include <algorithm>

using namespace std;

struct commodity{
    int p, q, v;
};

bool cmp(commodity a, commodity b)
{
    return a.q-a.p<b.q-b.p;
}

int main()
{
    int n, m;
    while(~scanf("%d%d", &n, &m))
    {
        commodity com[505] = {0};
        int dp[5005] = {0};
        for(int i=1;i<=n;i++)
            scanf("%d%d%d", &com[i].p, &com[i].q, &com[i].v);
        sort(com, com+n, cmp);
        for(int i=1;i<=n;i++)
            for(int j=m;j>=com[i].q;j--)
                dp[j] = max(dp[j], dp[j-com[i].p]+com[i].v);
        printf("%d\n", dp[m]);
    }
    return 0;
}
Published 152 original articles · won praise 22 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_38204302/article/details/105201166