首页 新闻 会员 周边

关于一个背包问题。

0
悬赏园豆:10 [已解决问题] 解决于 2014-04-24 18:48

#include<iostream>
#include<algorithm>
using namespace std;
struct abc
{
    float a;
    float b;
    float c;
};
bool comp(const abc e, const abc f)
{
    return (e.a)<(f.a);
}
int main()
{
    int n,i,sum1=0,sum2=0;
    float m,w,d;
    while(cin>>n>>m)
    {
        sum1=0;sum2=0;
        struct abc k[n];
        for(i=0;i<n;i++)
        {
          cin>>w>>d;
            k[i].c=w;
            k[i].b=d;
            k[i].a=d/w;
        }
        sort(k,k+n,comp);
        for(i=n-1;i>=0;i--)
        {
           sum1+=k[i].c;
           if(sum1<=m)
                sum2+=k[i].b;
        }
        cout<<sum2<<endl;
    }
    return 0;
}

 

我现在还没有学算法数据结构什么的,想问一下博园里的大牛们就现在的代码怎么改一下可以Ac?

问题补充:
Description

Bessie has gone to the mall's jewelry store and spies a charm bracelet. Of course, she'd like to fill it with the best charms possible from the N (1 ≤ N ≤ 3,402) available charms. Each charm i in the supplied list has a weight Wi (1 ≤ Wi ≤ 400), a 'desirability' factor Di (1 ≤ Di ≤ 100), and can be used at most once. Bessie can only support a charm bracelet whose weight is no more than M (1 ≤ M ≤ 12,880).

Given that weight limit as a constraint and a list of the charms with their weights and desirability rating, deduce the maximum possible sum of ratings.

Input

* Line 1: Two space-separated integers: N and M * Lines 2..N+1: Line i+1 describes charm i with two space-separated integers: Wi and Di

Output

* Line 1: A single integer that is the greatest sum of charm desirabilities that can be achieved given the weight constraints

Sample Input

4 6 1 4 2 6 3 12 2 7

Sample Output

23
尽善尽美#的主页 尽善尽美# | 初学一级 | 园豆:152
提问于:2014-04-23 17:25
< >
分享
最佳答案
0
#include<iostream>
#include<algorithm>
using namespace std;
struct abc
{
    float a;
    float b;
    float c;
};
bool comp(const abc e, const abc f)
{
     if(e.a!=f.a)  
        return e.a<f.a;
     else         // 考虑如果权重相等的时候,优先选择重量大的
        return e.c>f.c;
}
int main()
{
    int n,i,sum1=0,sum2=0;
    float m,w,d;
    while(cin>>n>>m)
    {
        sum2=0;
        struct abc k[n];
        for(i=0;i<n;i++)
        {
            cin>>w>>d;
            k[i].c=w;
            k[i].b=d;
            k[i].a=d/w;
        }
        sort(k,k+n,comp);
        i=n-1;
        while(m-k[i].c>=0)  //贪心选择
        {
           sum2+=(int)k[i].b;
           m-=k[i].c;
           i--;
        }
        cout<<sum2<<endl;
    }
    return 0;
}
收获园豆:10
Double_win | 菜鸟二级 |园豆:244 | 2014-04-24 17:34

谢谢你回答我的问题,在学校的服务器运行老是错误,在poj上直接都编译不了。。。可能因为这个吧 struct abc k[n];  我用的别的方法做了,不过还是感谢你

尽善尽美# | 园豆:152 (初学一级) | 2014-04-24 18:48

我知道错误的原因了,如下

(3)贪心策略:选取单位重量价值最大的物品。反例:

    W=30
    物品:A B C
    重量:28 20 10
    价值:28 20 10
    根据策略,三种物品单位重量价值一样,程序无法依据现有策略作出判断,如果选择A,则答案错误。
有必要学学算法了~

 

尽善尽美# | 园豆:152 (初学一级) | 2014-04-25 10:23
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册