hdu-3466 Proud Merchants(01背包之转移)

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=3466

题目很容易理解,但是如何将其转换为01背包是个问题。

对物品按 qi-pi 的值从小到大排序,因为这样可以保证每次更新的状态值从小到大递增,前面更新过的状态不会影响后面更新的状态。

题目代码:

 1 #include <iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 int n,m;
 7 int dp[5005];
 8 struct sa
 9 {
10     int p,q,v,u;
11 }a[505];
12 int cmp(const sa &a,const sa &b)
13 {
14     return a.u<b.u;
15 }
16 int main()
17 {
18     while(~scanf("%d%d",&n,&m))
19     {
20         for(int i=0;i<n;i++)
21         {
22             scanf("%d%d%d",&a[i].p,&a[i].q,&a[i].v);
23             a[i].u=a[i].q-a[i].p;
24         }
25         sort(a,a+n,cmp);
26         memset(dp,0,sizeof(dp));
27         for(int i=0;i<n;i++)
28         {
29             for(int j=m;j>=a[i].p;j--)
30             {
31                 if(j>=a[i].q)
32                 dp[j]=max(dp[j],dp[j-a[i].p]+a[i].v);
33             }
34         }
35         printf("%d
",dp[m]);
36     }
37     return 0;
38 }
View Code
原文地址:https://www.cnblogs.com/wang-ya-wei/p/5754673.html