zoukankan      html  css  js  c++  java
  • HDU 3466 Proud Merchants(背包问题,要好好理解)

    Problem Description
    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?

     
    Input
    There 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.
     
    Output
    For each test case, output one integer, indicating maximum value iSea could get.

    题意:01背包问题,就是用一定数量的钱可以购买到的最大的价值,但是在购买过程中会判断你拥有的钱是否小于某个值q,如果你的容量小于q,就无法购买,求可以买到的最大价值;
     
    题解:
    此题关键在于 发现购买商品会产生顺序的问题,

    其实就是dp后效性的问题,除了i和v这2个维度还多了一个维度q,直接套用公式无法去除后效性,
    先找到选择顺序的规律,去除后效性,再使用01背包;

    选取的规律: 比如A:p1 q1, B:p2 q2,然后,假设单独买A或者B的话,都是可以买到的。
    这时,若先买A,则你至少需要p1+q2的钱;若先买B,则至少需要p2+q1的钱。那肯定是花最少的钱咯,所以如果先买A再买B,那么p1+q2<p2+q1,
    转换一下,就是q1-p1>q2-p2,也就是说qi-pi大的先买。
    这里还得注意一点就是,排序的时候,得按照qi-pi从小到大排序,
    因为你买第n件商品的时候,是在比较你是否要先买第n件商品。
    打个比方让大家更好地理解,比如说f(3, 10),是不是max(f(2, 10-p3)+v3, f(2, 10)),
    你会发现这个第一种情况f(2,10-p3)+v3中,是先买了第三件商品,也就是说排在后面的商品会先买。(重点)

    还有一个要注意的:我们背包问题写的状态转移方程是从后往前选的(一维);

     
     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<algorithm>
     5 using namespace std;
     6 
     7 struct GOOD{
     8     int c, q, w;
     9 }g[507];
    10 
    11 bool cmp(GOOD x, GOOD y){
    12     return x.q-x.c<y.q-y.c;
    13 }
    14 
    15 int main()
    16 {
    17     int n, V, f[5007];
    18     while(cin>>n>>V)
    19     {
    20         memset(f, 0, sizeof(f));
    21         for(int i=1; i<=n; i++)
    22             cin>>g[i].c>>g[i].q>>g[i].w;
    23         sort(g+1, g+n+1, cmp);
    24 
    25         for(int i=1; i<=n; i++)
    26             for(int v=V; v>=g[i].q; v--)
    27                 f[v]=max(f[v], f[v-g[i].c]+g[i].w);
    28         cout<<f[V]<<endl;
    29     }
    30     return 0;
    31 }
     
  • 相关阅读:
    如何将baidu地图中的baidu logo 去掉
    漂亮的圆角文本框 CSS3实现
    jQuery数字加减插件
    腾迅股票数据接口 http/javascript
    JS复制内容到剪贴板(兼容FF/Chrome/Safari所有浏览器)
    关于编写性能高效的javascript事件的技术
    想做web开发 就学JavaScript
    git的简单理解及基础操作命令
    《CSS权威指南》基础复习+查漏补缺
    TypeScript Writing .d.ts files(编写声明文件)
  • 原文地址:https://www.cnblogs.com/Yokel062/p/10702180.html
Copyright © 2011-2022 走看看