题目描述

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?

题目大意

对于每一个物品,必须手上有一定的金额时才能购买,并且价格是p,价值是v,求最大的价值。

解法

非常容易可以发现,这道题的题干和01背包的题目异常的相似,不同的是有一个限制条件:在购买这个物品的时候手上必须要有一定的金钱。
那么我们就要考虑如何将这个限制条件加入到我们的动态规划中。
非常直接就可以得到如果我们当前枚举的花费\(j\)如果大于等于限制的话,那么就可以转移到f[j-b[i]]+v[i]。
但是我们会发现,如果一个物品的价值很大位置有很后面,但是这个物品的\(p\)和\(q\)的差值过大,那么就会让这个物品无法进入到状态中,那么就会使DP有后效性。
那么我们就需要进行排序,将那么限制和价格接近的放在前面,使01背包的规划成立。

代码

#include<bits/stdc++.h>
#define N 5005
#define inf 0x3f3f3f3f
using namespace std;
struct node{
    int a,b,v;
}s[N];
int f[N];
int n,m;
int r(){
    int w=0,x=0;char ch=0;
    while(!isdigit(ch))w|=ch=='-',ch=getchar();
    while(isdigit(ch))x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
    return w?-x:x;
}
bool cmp(node a,node b){return (a.b-a.a)<(b.b-b.a);}
int main(){
    while(scanf("%d%d",&n,&m)!=EOF){
        for(int i=0;i<=m;i++) f[i]=0;
        n=r(),m=r();
        for(int i=1;i<=n;i++) s[i].a=r(),s[i].b=r(),s[i].v=r();
        sort(s+1,s+1+n,cmp);
        for(int i=1;i<=n;i++){
            for(int j=m;j>=s[i].a;j--){
                if(j>=s[i].b) f[j]=max(f[j],f[j-s[i].a]+s[i].v);
            }
        }
        printf("%d\n",f[m]);
    }
    fclose(stdin); fclose(stdout);
    return 0;
}

最新文章

  1. {POJ}{3971}{Scales}{O(N)动态规划}
  2. [VSTS] 从零开始 Team Foundation Server 2010 安装配置详细图文教程
  3. 在 github 上获取源码
  4. Microsoft 2013 新技术学习笔记 一
  5. LeetCode45 Jump Game II
  6. LeetCode4 Median of Two Sorted Arrays
  7. 基础笔记(一)Java 集合
  8. php内存分析
  9. 将dom4j格式化为标准的xml字符串
  10. 代码编写规范说明书(c#.net与asp.net)
  11. myEclipse hibernate连接数据库配置方法
  12. 怎么避免在类实现的cpp文件中不要多次进行类声明
  13. vue element-ui 文件上传
  14. [Swift]LeetCode599. 两个列表的最小索引总和 | Minimum Index Sum of Two Lists
  15. Java的隐秘之JavaCC
  16. DHT网络
  17. 设置div 高度 总结
  18. Vmware Vcenter6.5 全新安装及群集配置介绍
  19. JAVA 实现XML与JSON 相互转换
  20. webSocket支持的浏览器

热门文章

  1. POI Sax 事件驱动解析Excel2003文件
  2. Ionic app 通知在Moto 360 Watch上显示通知(1)
  3. 多线程-synchronized、lock
  4. 使用IE浏览提示:该页面无法显示
  5. 第一章:模型层model layer -- Django从入门到精通系列教程
  6. [UWP 自定义控件]了解模板化控件(9):UI指南
  7. C#_面试
  8. 牛客训练赛25-A-因数个数
  9. Codeforces Round #505 (rated, Div. 1 + Div. 2, based on VK Cup 2018 Final)-C. Plasticine zebra
  10. db2安装