AlgorithmIdea: gradually construct the optimal solution in greedy method. Make a seemingly optimal decision at each stage (under certain standards ). Once a decision is made, it cannot be changed. The basis for making greedy decisions is greedy criterion ).
Container Shipping: a ship can be loaded step by step, each step of a container, and you need to consider loading that container. Based on this idea, we can use the following greedy principle: from the remaining boxes, we can select the boxes with the smallest weight. This selection order can minimize the weight of the selected box, so that more boxes can be loaded. According to this greedy strategy, first select the lightest box, and then select the light box, so that until all the boxes are loaded on the ship or the ship cannot accommodate any other boxes.
ImplementationCode:
Void indirectsort (int w [], int T [], int N)
{
Int I, j, temp;
For (I = 0; I <n; ++ I)
T [I] = I;
For (I = 1; I <n; ++ I ){
Temp = T [I];
For (j = I; J-1> = 0 & W [T [J-1]> W [temp]; -- J)
T [J] = T [J-1];
T [J] = temp;
}
}
Template <typename T>
Void containeloading (int x [], t w [], t C, int N)
{// Greedy algorithm for container shipping Problems
// X [I] = 1 When and only when I is loaded, 1 <= I <= N
// C indicates the capacity of the ship and W indicates the weight of the freight box.
// Sort weights by indirect addressing
// T is an indirect addressing table
Int * t = new int [n + 1];
Indirectsort (W, t, n );
// At this time, W [T [I] <= W [T [t + 1], 1 <= I <n
// Initialize x
For (INT I = 1; I <= N; ++ I)
X [I] = 0;
// Select items by weight
For (INT I = 1; I <= N & W [T [I] <= C; ++ I ){
X [T [I] = 1;
C-= W [T [I]; // remaining capacity
}
Delete [] T;
}