贪心算法之最优装载问题

问题描述:

有一批集装箱要装上一艘载重量为c的轮船。其中集装箱i的重量为Wi。最优装载问题要求确定在装载体积不受限制的情况下,将尽可能多的集装箱装上轮船

最优装载问题可用贪心算法求解。采用重量最轻者先装的贪心选择策略,可产生最优装载问题的最优解

代码:

#include<iostream>
using namespace std;
 
int n;//number
int Weight;//Maxload
int w[100];//weight
int x[100];//0,1
int t[100];//index
int Count;//counter
void input()
{
    cout<<"货物个数:"<<endl;
    cin>>n;
    cout<<"最大承重:"<<endl;
    cin>>Weight;
    cout<<"重量数组:"<<endl;
    for(int i=0;i<n;i++)
    cin>>w[i];
}
void Sort()
{
    for(int i=0;i<n-1;i++)
    {
        for(int j=0;j<n-i-1;j++)
        {
            if(w[j]>w[j+1])
            {
                int temp1=w[j];
                w[j]=w[j+1];
                w[j+1]=temp1;

                int temp2=t[j];
                t[j]=t[j+1];
                t[j+1]=temp2;
            }
        }
    }
}
void loading()
{
    for(int i=0;i<n;i++)
    t[i]=i;
    int c=Weight;
    Sort();
    for(int i=0;i<n&&w[i]<=c;i++)
    {
        x[t[i]]=1;
        Count++;
        c-=w[i];
    }
}
int main()
{
    input();
    loading();
    cout<<"装载最大数:"<<Count<<endl;
    cout<<"选择向量:"<<endl;
    for(int i=0;i<n;i++)
    {
        cout<<x[i]<<" ";
    }
    cout<<endl;
    system("pause");
    return 0;
}

运行截图:

 

  • 3
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值