Greedy method--boat problem

Source: Internet
Author: User

The topics are generally:
There are n individuals, the personal weight of w[i], the maximum load per ship is C, and can only be up to two people. Load the owner with the fewest ships.

Solution:
First of all, from the lightest, he should sit with the heaviest man, and if everyone could not ship with it, then the only way is for everyone to be a boat.
Otherwise, he should choose the heaviest person who can take a boat with him, and this will not be wasted.

#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream>using namespace Std;struct Node{int W;} A[1001];bool CMP (node A,node b) {return A.W<B.W;} int main () {int i,j,n,c;int book[1001]={0};scanf ("%d%d", &n,&c), for (i=1;i<=n;i++) scanf ("%d", &A[I].W) ; sort (a+1,a+1+n,cmp); int num=0;for (i=1;i<=n;i++) {//book[i]=1; for (j=n;j>=1;j--) {//one: If they are two weight and less than or equal to C, And J This man has not been pulled away by others, then this is a kind; if (a[i].w+a[j].w<=c && book[j]==0) {num++; book[i]=1; book[j]=1; break;} Two: If they weigh two and greater than C and J is not pulled, then J will only be able to sit alone with himself in a boat; else if (a[i].w+a[j].w>c && book[j]==0) {num++; Book[j]=1; }}//If the above are all circulating, but I still do not meet the conditions, then it is also only to sit on their own boat, if (!book[i])  {num++; book[i]=1;}} printf ("%d\n", num);}


Greedy method--boat problem

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.