boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 背包问题
相关主题
问题:从电话号码打出所有单词
写了一个find kth number in 2 sorted arrays的code 请大牛看
two sigma 的online code test 的问题
leetcode上一题,求正解
请问为什么这个程序会出现RunTime Error
这题你肯定见过,但有准备coding么?
C++ Q 99-102
google电面面经
你们看过programming pearls (2nd edition English) or 正在看的同学们
one c++ question
相关话题的讨论汇总
话题: int话题: ind话题: vector话题: tvalue话题: tind
进入JobHunting版参与讨论
1 (共1页)
s*w
发帖数: 729
1
codeeval.com 上的一个题
给n个东西,每个东西有重量和价值,要求在重量小于给定值的时候,尽量价值大
在重量是浮点数的情况下,怎么做 bottomup 的 dp table?
我现在的解是 recursion, 而且没 memorization, 因为不知道怎么存这个 table.
帖下代码,请指教一下
#include
#include
#include
#include
#include
#include
using namespace std;
class Solution {
int weightLimit;
int n;
vector weights;
vector costs;
public:
Solution(const string &line) {
istringstream iss(line);
iss >> weightLimit;
int ind,cost;
double weight;
do {
iss.ignore(256,'(');
iss >> ind;
iss.ignore(256,',');
iss >> weight;
iss.ignore(256,'$');
iss >> cost;
iss.ignore(256,')');
if(iss.good()) {
weights.push_back(weight);
costs.push_back(cost);
}
} while(iss.good());

n = weights.size();
}
vector run2(double wlimit, vector ind) {
vector bestInd;
int bestValue = 0;
for(int i=0;i vector tInd;
int tValue = 0;
double wlimit2 = wlimit - weights[ind[i]];
if(wlimit2 > 0) {
// update tValue and tInd due to chosing a valid ind[i]
tValue += costs[ind[i]];
tInd.push_back(ind[i]);
// solve subproblem
vector ind2(ind);
ind2.erase(ind2.begin()+i);
vector ret2 = run2(wlimit2,ind2);
if(!ret2.empty())
// update tValue and tInd due to valid subproblem solution
for(auto j : ret2) {
tValue += costs[j];
tInd.push_back(j);
}
}
// update best if necessary
if(tValue>bestValue) {
bestValue = tValue;
bestInd = tInd;
}
}
return bestInd;
}
void run() {
vector ind;
for(int i=0;i ind.push_back(i);
vector ret = run2(weightLimit,ind);
if(ret.empty())
cout << "-" << endl;
else if(ret.size()==1)
cout << ret[0]+1 << endl;
else {
for(int i=0;i cout << ret[i]+1 << ",";
cout << ret[ret.size()-1]+1 << endl;
}
}
};
int main(int argc,char* argv[]) {
if(argc<2)
throw invalid_argument("need 1 parameter");
ifstream ifs(argv[1]);
string line;
while(getline(ifs,line)) {
Solution sol(line);
sol.run();
}
}
b**********5
发帖数: 7881
2
google knapsack
a********m
发帖数: 15480
3
浮点的话是麻烦,毕竟是伪多项式。不过一般价格位数有限,弄成整数也还能做。

【在 s*w 的大作中提到】
: codeeval.com 上的一个题
: 给n个东西,每个东西有重量和价值,要求在重量小于给定值的时候,尽量价值大
: 在重量是浮点数的情况下,怎么做 bottomup 的 dp table?
: 我现在的解是 recursion, 而且没 memorization, 因为不知道怎么存这个 table.
: 帖下代码,请指教一下
: #include
: #include
: #include
: #include
: #include

1 (共1页)
进入JobHunting版参与讨论
相关主题
one c++ question
C的argc问题
为什么我这段简单的程序segment fault
c++ 程序一问
bloomberg assessment的机经,c语言的(20道题)
C++ online Test 又一题
C++ 一题
这题哪错了?
这个看着很白痴的问题有更好的解法吗?
帮看看这段code
相关话题的讨论汇总
话题: int话题: ind话题: vector话题: tvalue话题: tind