大致題意:有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從大到小的順序)進行排序,然而事實並非這樣!!!請往下看(網上大神的解釋......)
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?
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 3Sample 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;
}