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