Boating Problem [Classic Greed]

Topic link: http://www.bjfuacm.com/contest/115/problem/565/

                                                       boat problem

                                            Release time: April 24, 2018 15:21 Time limit: 1000ms Memory limit: 128M

There are n people, and the weight of the ith person is w[i]. Each boat has a maximum carrying capacity of C and can only carry a maximum of two people. How can I load everyone with the least amount of boats.

Enter multiple sets of data. Enter two integers n and C in the first line of each set of data, indicating that there are n people, and the maximum carrying capacity of each ship is C, and enter n integers w[i] in the second line, indicating the weight of each person. All data are in [1, 1000], and for all w[i], there is w[i] <= C.

Corresponding to each set of data, an integer is output, indicating the minimum number of ships that are used by everyone.

3 100
50
90
40
2 Problem- 

solving ideas:
Arrange the weights of all people in ascending order. If the current person with the smallest weight plus the person with the largest weight is still <= the total capacity of the boat, let them ride on the same boat. Doubt, this is the least wasted space on the ship, so it can be seen that this allocation is optimal.
If the current
person with the smallest weight plus the person with the heaviest weight >= the capacity of the boat, then only the person with the current heaviest weight can sit on a boat alone.
 
  
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int i, n, w[1010], c;
    while (scanf("%d%d", &n, &c) != EOF)
    {
        for (i = 0; i<n; i++)
            scanf("%d", &w[i]);
        sort(w, w + n);
        int sum = 0;
        i = 0;
        while (i<n)
        {
            if (w[i] + w[n - 1 ] <= c)           // If the heaviest and the smallest weight can take a boat, then let them take a boat, and continue to repeat these operations for the rest of the people 
            {
                i++;
                n--;
                sum++;
            }
            else                                // If the current weight of the smallest plus the largest will exceed c, then only the heaviest can take a boat alone 
            {
                n--;
                sum++;
            }
        }
        printf("%d\n", sum);
    }
    return 0;
}
 
  
2018-04-25

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324856123&siteId=291194637