Want to determine if there is a way to ship all n containers in full. If so, find out the method.
Main idea: to ask for the maximum load of the first ship. Each kind of cargo has and does not have two kinds of cases, n goods of the trade-off combination of 2^n sub-branch, the use of branch search method to seek optimization problems.
C + + code:
#include <iostream>#include <queue>#include <vector>using namespace STD;DoubleMaxloading (Const vector<double>&w,Const DoubleC1) {DoubleBESTW =0; Queue<double>Qwintn = w.size ();//-1 means the tail of the arrival layerQw.push (-1);//Current weight DoubleEW =0;//Box I cargo inti =0; while(!qw.empty ()) {//Put box I cargo if(EW + w[i] <= C1) {Qw.push (ew+w[i]);if(EW + w[i] > BESTW) {BESTW = ew +w[i]; } }//Do not put box I cargoQw.push (EW); ew = Qw.front (); Qw.pop ();//If the first layer is over if(-1= = ew) {//If the last box of cargo is considered if(i = = n1) {returnBESTW; }Else{Qw.push (-1); }//If the squad is-1, then one more elementew = Qw.front (); Qw.pop (); ++i; } }}intMain () {DoubleC1,C2;cout<<"Please enter C1,C2:";Cin>>c1>>c2;cout<<"Please enter the weight of the N containers:"; vector<double>WDoubleTmp_w;DoubleTotal_w =0; while(Cin>>tmp_w) {w.push_back (tmp_w); Total_w + = Tmp_w; }if(Total_w <= C1 | | total_w <= c2) {cout<<"a boat!"<<endl;Exit(0); }if(Total_w > C1+c2) {cout<<"Unable to load!" "<<endl;Exit(0); }DoubleMC1 = maxloading (W,C1);if(TOTAL_W-MC1 <= C2) {cout<<"can be loaded!" "<<endl;cout<<"first ship."<<Mc1<<' \ t '<<"A second ship."<<total_w-Mc1<<endl; }Else{cout<<"Unable to load"<<endl; }return 0;}//50// +
Operation Result:
There are two ships need to ship N Box cargo, the first ship's load capacity is C1, the second ship's load capacity is C2,wi is the weight of the container I, and w1+w2+......+wn<=c1+c2.