集装箱装载问题

来源:互联网 发布:iphone6s蜂窝移动网络 编辑:程序博客网 时间:2024/04/30 07:48

题目详情:有一批n个集装箱要装上两艘载重量分别为weightone,weighttwo的轮船,其中,集装箱i的重量为weight【i】,现在要确定是否存在一个合理的装载方案可以把所有的集装箱装上这两个轮船。

实现代码:

#include <iostream>#include <vector>#include <algorithm>using namespace std;int totalweight=0,weightone,weighttwo,num;vector<int>weight;   //假设最多有100个集装箱vector<bool>visited;bool mark=false;void select(int start,int wantselect,int selected,int selectedweight){    if(mark)    {        return;    }    if(wantselect==selected)    {        if(selectedweight<=weightone&&totalweight-selectedweight<=weighttwo)        {            cout<<"第一个箱子装的集装箱编号为:"<<endl;            for(int j=0;j!=visited.size();j++)            {                if(visited[j]==true)                {                    cout<<j<<endl;                }            }            cout<<"第二个箱子装的集装箱编号为:"<<endl;            for(int i=0;i!=visited.size();i++)            {                if(visited[i]==false)                {                    cout<<i<<endl;                }            }            mark=true;        }    }    for(int k=start;k<num;k++)    {        if(!visited[k])        {            visited[k]=true;            select(k+1,wantselect,selected+1,selectedweight+weight[k]);            visited[k]=false;        }    }}int main(){    int tmp;    cin>>num;    for(int i=0;i<num;i++)    {        cin>>tmp;        weight.push_back(tmp);        visited.push_back(false);        totalweight+=tmp;    }    cin>>weightone>>weighttwo;    for(int j=0;j<num;j++)    {        select(0,j+1,0,0);    }    if(!mark)    {        cout << "无解" << endl;    }    return 0;}

具体原理和上一篇文章部落卫队问题类似。

原创粉丝点击