Greedy Algorithm-Freight box shipping + read data structure Algorithm and Application-C ++ language description

Source: Internet
Author: User

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;
}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.