hdu3466 Proud Merchants

大致題意:有n組數,每組數有三個數,pi,買這種物品你有的錢必須大於qi,你所能獲得的價值vi。如果你想要買這種物品你所擁有的錢必須大於qi。

問你能用你所有的錢最多能獲得多大價值。


解題思路:以第二組數據爲例:A:5 10 5  B:3  5   6如果先買A的再買B的話需要花10塊錢,但是先買B再買A的話需要13塊錢。也就是花不同的錢卻獲得了相同的價值。所以這裏排序就比較關鍵了!怎麼排呢?還是以上面爲例,先買A再買B花費p1+q2,先買B再買A花費p2+q1,p1+q2<p2+q1(爲了使數據滿足一定的順序進行購買,因此我們使所有的數據都按照(q1-p1>q2-p2)這樣的順序排序,這樣購買最終我們所需的錢數就是最少的,也就是拿同樣多的錢,我們可以買更大價值的東西!在這裏p1+q2<p2+q1與q1-p1>q2-p2等價,只不過在這裏我們將描述同一個物體的變量放到不等式的一邊(q1-p1>q2-p2),然後再進行排序操作比較方便罷了),如果我們都按照這樣的順序(qi-pi從大到小的順序)進行排序,然而事實並非這樣!!!請往下看(網上大神的解釋......)

   其實01揹包的購買都是按照從後向前的順序進行購買的,也就是說,它的每次的最後一個商品是確定購買的,然後再加上前面的除下用的最後一個的錢之後能夠夠購買的最大的價值與不購買這個物品進行比較,哪個大就選哪個!(在這個過程中因爲是先確定後面的物品是否購買,所以我們要將差值(qi-pi)大的放到後面,差值小的放到前面,也就是前面說的按照從大到小的順序是進行購買的順序,而真正排序,然後按照揹包執行程序的時候是按照從小到大的順序!)
          總之,就是按照差值(qi-pi)從小到大排序,然後用01揹包的方法進行操作就行了!
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? 

InputThere 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. 

OutputFor 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<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,m,p[1010],q[1010],v[1010],dp[1010][5010];
struct node
{
    int p,q,v;
} a[1010];
int cmp(node a,node b)
{
    return (a.q-a.p)<(b.q-b.p);
}
int main()
{
    int i,j;
    while(~scanf("%d%d",&n,&m))
    {
        memset(dp,0,sizeof(dp));
        for(i=1; i<=n; i++)
        {
            scanf("%d%d%d",&a[i].p,&a[i].q,&a[i].v);
        }
        sort(a+1,a+n+1,cmp);//按照差價從小到大排序
        for(i=1; i<=n; i++)
        {
            for(j=0; j<=m; j++)
            {
                dp[i+1][j]=dp[i][j];
                if(j>=a[i].q)//只有大於去a[i].q才能購買
                {
                    dp[i+1][j]=max(dp[i][j],dp[i][j-a[i].p]+a[i].v);
                }
            }
        }
        printf("%d\n",dp[n+1][m]);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章