【问题标题】:Getting problems in my knapsack implementation(PARTY)在我的背包实施中遇到问题(PARTY)
【发布时间】: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


    【解决方案1】:

    问题中的代码没有通过Dynamic Programming 实现精确解决方案,而是一种通常不会计算最佳解决方案的贪心算法。但是,问题中链接中的任务显然需要生成最佳解决方案。

    贪心算法的次优性可以通过考虑下面的例子来证明。

    Item 1: Function 6, Cost 4 (Ratio 18/12)
    Item 2: Function 4, Cost 3 (Ratio 16/12)
    Item 3: Function 3, Cost 3 (Ratio 12/12)
    
    Capacity: 6
    

    贪心算法会选择Item 1,产生6的利润。但是选择Item2Item3 会产生7 的总利润。

    【讨论】:

    • 嗯,真的吗?我不明白。你为什么这么认为 ?我的意思是,我在计算b/w fun和cost的比率,然后按降序排序并找到解决方案。我阅读了this method of solve 0/1 integer knapsack problem via this method...
    • @Nib 你在哪里读到的?它并不总是给出最佳解决方案。这个答案是正确的。
    猜你喜欢
    • 1970-01-01
    • 2020-08-07
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    相关资源
    最近更新 更多