HDU 3466 Proud Merchantss

来源:互联网 发布:jquery数组删除元素吗 编辑:程序博客网 时间:2024/06/13 12:38

如果哪里讲错,欢迎大神指出!!!


这是一个01背包的变种问题,因为加了q。题意很简单。

很多题解上面都说要按照q-p顺序排列,一开始我还没弄懂,所以度娘求解,直到在别人博客里面得到解答



这题因为涉及到q,所以不能直接就01背包了。因为如果一个物品是5 9,一个物品是5 6,对第一个进行背包的时候只有dp[9],dp[10],…,dp[m],再对第二个进行背包的时候,如果是普通的,应该会借用前面的dp[8],dp[7]之类的,但是现在这些值都是0,所以会导致结果出错。于是要想到只有后面要用的值前面都可以得到,那么才不会出错。设A:p1,q1 B:p2,q2,如果先A后B,则至少需要p1+q2的容量,如果先B后A,至少需要p2+q1的容量,那么就是p1+q2 > p2+q1,变形之后就是q1-p1 < q2-p2。

这段解释来自于:http://www.cnblogs.com/andre0506/archive/2012/09/20/2695841.html


下面就是ac code:

#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <cstdlib>#include <cmath>#include <vector>#include <list>#include <deque>#include <queue>#include <iterator>#include <stack>#include <map>#include <set>#include <algorithm>#include <cctype>using namespace std;#define si1(a) scanf("%d",&a)#define si2(a,b) scanf("%d%d",&a,&b)#define sd1(a) scanf("%lf",&a)#define sd2(a,b) scanf("%lf%lf",&a,&b)#define ss1(s)  scanf("%s",s)#define pi1(a)    printf("%d\n",a)#define pi2(a,b)  printf("%d %d\n",a,b)#define mset(a,b)   memset(a,b,sizeof(a))#define forb(i,a,b)   for(int i=a;i<b;i++)#define ford(i,a,b)   for(int i=a;i<=b;i++)typedef long long LL;const int N=1100001;const int M=6666666;const int INF=0x3f3f3f3f;const double PI=acos(-1.0);const double eps=1e-7;struct p{    int price,q,value;}a[505];bool cmp(p a, p b){    if(a.q-a.price==b.q-b.price)        return a.q>b.q;    return a.q-a.price<b.q-b.price;}int dp[5005];int main(){    int n,m;    while(~scanf("%d%d",&n,&m))    {        forb(i,0,n)        scanf("%d%d%d",&a[i].price,&a[i].q,&a[i].value);        sort(a,a+n,cmp);        mset(dp,0);        forb(i,0,n)        {            for(int j=m;j>=a[i].price;j--)            {                if(j<a[i].q)                    break;                dp[j]=max(dp[j],dp[j-a[i].price]+a[i].value);            }            //printf("%d\n",dp[m]);        }        printf("%d\n",dp[m]);    }    return 0;}


0 0
原创粉丝点击