Question: There are n people. The weight of the I-th person is wi. The maximum carrying capacity of each ship is C, and only two people can be taken at most. Use the least ship to load the owner.
Analysis: greedy!
Who should I sit? If everyone cannot get on a ship with him, the only solution is that everyone can get on a ship!
Otherwise, he should choose the heaviest j among the people who can take the boat with him.
This method is greedy! Because: it only makes the "present" Waste the least.
Program Implementation: we only need to use two subscripts I and j to represent the lightest and heaviest people currently under consideration, moving j to the left each time, until I and j can take a ship together, then I plus 1, j minus 1. Repeat the preceding operations!
The complexity is o (n ).
Code:
# Include
# Include
# Include using namespace std; const int MAXN = 10000; int arr [MAXN]; int main () {int n, C; // C indicates the maximum carrying capacity of each ship. cin> n> C; for (int I = 1; I <= n; ++ I) {cin> arr [I];} sort (arr + 1, arr + n + 1); int I = 1, j = n; int ans = 0; while (I <j) {if (arr [I] + arr [j]> C) j --; else if (arr [I] + arr [j] <= C) {ans ++; I ++; j -- ;}} cout <ans + n-(2 * ans) <endl; return 0 ;}
The final output should be the number of pairs + the remaining number!
Remaining persons = Total Persons n-minus successful persons!
Successful pairing COUNT = 2 * ans.
Ans indicates the pair logarithm!