【发布时间】:2015-01-21 10:53:48
【问题描述】:
我今天尝试从 spoj 做this simple question,这是背包问题,我已实现如下:
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int main(void)
{
while(true)
{
int budget, t;
scanf("%d%d", &budget, &t);
if(budget == 0 && t == 0)
break;
int cost[t], fun[t];
vector<pair<double, int> > knap;
for(int i = 0;i < t;i++)
{
scanf("%d%d", &cost[i], &fun[i]);
knap.push_back(pair<double, int>(double(fun[i])/double(cost[i]), i));
}
sort(knap.rbegin(), knap.rend());
int totfun = 0, bud = budget;
for(int i = 0;i < int(knap.size());i++)
{
if(bud - cost[knap[i].second] >= 0)
{
bud -= cost[knap[i].second];
totfun += fun[knap[i].second];
}
}
printf("%d %d\n", budget-bud, totfun);
}
}
但是这个解决方案给出了 WA(错误答案)。我已经在spoj自己的论坛中尝试了所有测试用例,我的代码似乎都通过了,谁能指导我,这是我尝试过的第一个DP问题...
【问题讨论】:
标签: c++ algorithm dynamic-programming knapsack-problem