Boat problems are simple and greedy

Source: Internet
Author: User

Question:

Given the maximum carrying capacity, the number of passengers, and the weight of each passenger, a maximum of two persons can be taken on each ship, and the minimum number of ships required for each passenger to get on the ship.

Because the passenger's weight range is small, all possible weights can be directly traversed, saving the sorting of the passenger's weight values. Use an array to record the number of passengers of each weight, and obtain the optimal solution based on the optimal combination of passengers of the lighter weight and passengers of the heavier weight.

Code:

# Include <iostream>
# Include <cstring>
Using namespace STD;

Int main (){
Int A [300];
Int m, n, I, j;
Cin> m> N;
Memset (A, 0, sizeof ());
Int min = 10000, max =-1;
For (I = 1; I <= N; I ++ ){
Cin> J;
A [J] ++;
If (j <min) min = J;
If (j> MAX) max = J;
}
J = m-min; // J is the heaviest passenger
I = min; // I is the lightest passenger
Int msum = 0;
While (I <= max ){
If (2 * I <= m ){
If (m-I <j) J = m-I; // search for heavy passengers in descending order
While (A [J] = 0) j --; // skip the nonexistent weight
If (j = I ){
Msum + = (a [I] + 1)/2; // if there are odd numbers, one person takes a boat.
A [I] = 0;
}
Else {// I, j, and so on. Then, in I, j, find the one with a small number to form a pair of two persons in min. At the same time, the number of J is reduced by Min.
Int K = A [I]> A [J]? A [J]: A [I];
Msum + = K;
A [I]-= K;
A [J]-= K;
}
}
Else {// If 2 * I> M, you can only sit on the ship by one person, add a [I] boat, and clear a [I]
Msum + = A [I];
A [I] = 0;
}
While (I <= max & A [I] = 0) // find the next light passenger
I ++;
}
Cout <msum;
Return 0;
}

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.