ACM: greedy: Boat problem.

Source: Internet
Author: User

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!

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.