算法设计与分析——贪心算法——最优装载问题
生活随笔
收集整理的這篇文章主要介紹了
算法设计与分析——贪心算法——最优装载问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
有一批集裝箱要裝上一艘載重量為c的輪船。其中集裝箱i的重量為Wi。最優裝載問題要求確定在裝載體積不受限制的情況下,將盡可能多的集裝箱裝上輪船。
#include<iostream> #include<algorithm> #include<cstring> using namespace std;typedef struct Node {int number;//序列中的第幾個 int weight;//序列的重量 }node; bool cmp(node x,node y) {if(x.weight<y.weight)return true;elsereturn false;} void Loading(int *result,int *weight,int capacity,int n) {Node node[n+1];for(int i=1;i<=n;i++){node[i].number=i;node[i].weight=weight[i];}sort(node+1,node+n+1,cmp);cout<<"貨物按重量排好序為:"; for(int i=1;i<=n;i++){cout<<node[i].weight<<" ";weight[i]=node[i].weight;}cout<<endl;for(int i=1;i<=n;i++){result[i]=0;}int pre=1;int c=capacity;for(int i=1;i<=n;i++){if(weight[i]<=c){result[i]=1;c=c-weight[i];}else{break;}}} int main() {cout<<"輸入集裝箱的數量:";int n;cin>>n;cout<<"輸入輪船所能承擔的最大重量:";int capacity;cin>>capacity;cout<<"輸入集裝箱的重量序列:";int weight[n+1];for(int i=1;i<=n;i++){cin>>weight[i];}int result[n+1];Loading(result,weight,capacity,n);for(int i=1;i<=n;i++){cout<<result[i]<<" ";}}總結
以上是生活随笔為你收集整理的算法设计与分析——贪心算法——最优装载问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 贾跃亭称中东市场具有非常独特的优势 翻译
- 下一篇: 新华三管理层集体降薪:17 级以上主动降