您的位置:首页 > 其它

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
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: