Backtracking Method to Find the Optimal Loading Problem

There is a batch of containers to be loaded on a ship of capacity c. where the weight of container i is wi. The optimal loading problem asks to determine how few containers can be loaded onto a ship, given that the loading volume is unlimited.

For example: n=5, W=10, w={5,2,6,4,3}
loading scheme: (1,1,0,0,1) (0,0,1,1,0)
so the most The optimal loading plan is the 3rd and 4th container

Problem Representation: Global Variables

int w[]={0,5,2,6,4,3}; The first 0 does not mean
int n=5, W=10, that is, there are five containers, and the maximum load capacity of the ship is 10

If you choose this box, it is 1, if you do not choose this box, it is 0, so the representation of the solution vector

int maxW ; //store the total weight of the optimal solution, the initial value is 0
int x[MAIN];//store the optimal solution vector, the initial value is 0, that is, take this box or not
int mainNum=99999;// The number of containers storing the optimal solution, the initial value is the maximum

Solving algorithm:

void dfs(int num, int tw, int rw, int op[], int i)
num: indicates the number of selected containers
tw: indicates the sum of the weights of the selected containers
rw: the weight sum of the remaining containers
op: indicates a solution , that is, an option
i: represents the considered container i

Understanding and application of void dfs(int num, int tw, int rw, int op[], int i):

For a node in the i-th layer, the corresponding calling state is dfs(num,tw.rw,op,i+1)
(1) If you want to select the i-th node, that is, the i-th container,
op[ i]=1,num=num+1,tw=tw+w[i],rw=rw-w[i], then
go to the next state: dfs(num,tw,rw,op,i+1)
This decision corresponds to the left branch, that is, choose this node
(2) If you do not choose the i-th node
op[i]=0, num remains unchanged, tw remains unchanged, rw=rw-w[i],
then turn Go to the next state: dfs(num,tw,rw,op,i+1)
This decision corresponds to the right branch, that is, this node is not selected

Pruning method:

Left pruning:
tw+w[i]<=W then expand, otherwise not expand

Right pruning:
tw+rw-w[i]>=W, then expand, otherwise not expand
that is: if the sum of the weights of all containers minus the weight of the current node i is greater than the maximum loading capacity of the ship, then expand This right branch, otherwise there is no need to expand
at all Then optimize it again:
tw+rw-w[i]>maxW then expand, otherwise do not expand

Guess you like

Origin blog.csdn.net/qq_46161529/article/details/122093784
Recommended