当前位置:首页 » 《随便一记》 » 正文

最优装载问题--贪心算法

29 人参与  2022年11月28日 17:13  分类 : 《随便一记》  评论

点击全文阅读


#include<iostream>#include<string>#include<memory.h>#include<cstdio>#include<string>#include <algorithm>#define NUM 1001using namespace std;int charaNum[NUM] ;//存放输入数据的数组int tempArr[NUM];struct load{    int weight;    int index;}arr[NUM];int x[NUM];bool cmp(const load & a, const load & b){    return a.weight<b.weight? true: false;}int greedySelect(load * A ,int num,int c){    int sum = 0;    int cleft = c;    int i = 0;    while(i<num && cleft>=A[i].weight)    {        cleft-=A[i].weight;        sum++;        x[A[i].index] = 1;        i++;    }    return sum;}int main(){    freopen("in.txt","r",stdin);    int weight ;    int num;    while(cin>>weight>>num)    {        memset(x,0 ,sizeof(x));        for(int i= 0;i<num;i++)        {            cin>>arr[i].weight;            arr[i].index=i;        }        stable_sort(arr,arr+num,cmp);        int sum = greedySelect(arr,num,weight);        if(sum == 0)        {            cout<<"No answer!"<<endl;        }        else        {            cout<<sum<<endl;        }        for(int i = 0;i<num;i++)        {            if(x[i] == 1)            {                cout<<i+1<<" ";            }        }        cout<<endl;    }}

输入:

50 340 10 4037 510 30 24 35 4025 330 40 50

输出:

2
1 2
2
1 3
No answer!


点击全文阅读


本文链接:http://zhangshiyu.com/post/49209.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1