hdu 4508
2016-04-19 21:23
239 查看
hdu 4508 这个问题的核心就是下面最长的那个公式,额也写了很长(但没什么用)的注释,首先注意,这里运用了一下压缩的办法,原本这里是二重循环,因此这里也应该开二维数组,不过这个问题没有必要,只要在原有数据上动手即可,因此第一层循环只当是计数而已了。 那么再来详细看看这个公式,首先需要明白一个问题,每一次更新的数据(以没有压缩为例),都是在当时的情况下的最优解,因此该算法实质上相当于是最优解的转移,再看看max函数内部,左边不讲了,没拿相当于该物品不存在,右边,这里需要一个“跳”的过程,从考虑当前问题跳到考虑之前某个最优解+当前手里的物品的情况,由于不拿的情况已经考虑过了,因此这个地方只能是强制拿,那么就回到之前某个状态,如果当时直接拿的这个物品,情况是否会好于之前的最优解?这个过程就是两个数进行比较的过程,比较结果作为新的最优解呈现出来覆盖更新原有的数据 不明白?想想图论那边,松弛,和这个差不多,起点到点k的最短距离等于起点到k-1的最短距离+k-1到k的距离(假设存在),只不过这个没有经过if的过程而是直接从赋值上体现了,其实也可以改成if的形式,就是先比较拿这个物品和之前的最优解然后再赋值而已。
#include<cmath> #include<cctype> #include<cstring> #include<algorithm> #include<numeric> #include<vector> #include<set> #include<map> #include<queue> #include<list> #include<stack> using namespace std; struct item { int v;//means Value int c;//means Cost item(int a, int b) :v(a), c(b) {};//constructor function }; vector<item>items;//store datas of all the items. vector<int>pro; int fun(int kind) { int v, c; for (int p = 0; p < kind; p++) { scanf("%d%d", &v, &c);//input items.push_back(item{ v,c }); } int lim; scanf("%d", &lim); //input pro.resize(lim + 1); for (int p = 0; p < kind; p++) { for (int i = 0; i <= lim; i++) { pro[i] = max(pro[i], i - items[p].c >= 0 ? pro[i - items[p].c] + items[p].v : 0);//the core of this algo, the left side means if i dont pick this item, and the right side means if i pick this item, for more explaination, visit the rest of this article } } return pro.back(); } int main(void) { //freopen("vs_cin.txt", "r", stdin); int kind; while (~scanf("%d", &kind)) {//input//这里长见识了,以前都是scanf,这个波浪线的意义……听说是取反,没错,默认EOF是-1,会被当成true,非一下就成0了 printf("%d\n", fun(kind));//output items.clear(); pro.clear();//the second time forgetting to clear, which caused a lot of out of range exception } }
相关文章推荐
- hdu 4508
- Leetcode—— trapping-rain-water
- 关于Android Toast
- CocoasPod与GitHub的区别
- kvm虚拟机常用命令
- JavaScript uploadify插件上传文件问题
- Android Multimedia Framework overview(多媒体框架概述)--base on jellybean(一)
- QT中QSystemTrayIcon
- CodeForces 638D Three-dimensional Turtle Super Computer
- 提取不重复的整数之机试
- 输出各种形式的分数
- hiho 36 划分
- 【城会玩系列】ZOJ 3212 K-Nice【思维】
- Kali nslookup命令详解
- CSS学习笔记
- 九度 1022
- 数据结构--二叉树的遍历
- Oracle-SQL03
- JavaScript学习笔记
- Kali 虚拟机 安装vmtools依旧无法复制粘贴解决办法