(Code forces) Taxi

After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?

Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, …, sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group.

Output
Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus.

Examples
input
5
1 2 4 3 3
output
4
input
8
2 3 4 4 2 1 3 1
output
5
Note
In the first test we can sort the children into four cars like this:

the third group (consisting of four children),
the fourth group (consisting of three children),
the fifth group (consisting of three children),
the first and the second group (consisting of one and two children, correspondingly).
There are other ways to sort the groups into four cars.

解题思路:
解题思路:分别统计人数为1,2,3,4小组的个数,,人数为4的小组直接可以算一辆车;
人数为3的小组和人数为1的小组配对,若人数为3的小组多于人数为1的小组,那么人数为3的小组都算一 辆车,再2与2配对,若人数为2的组数%2 == 0,车数=2的组数/2;否则再多加一个1留个那个剩余的2

若人数为3的小组小于人数为1的小组,那么人数为3的小组都算一辆车,人数为1的小组个数需要-人数为3的小组个数;接着2与2配对同上,只不过若有剩余的2可以用1配对;若还有1剩余,则只能自己配对了,/4即可,若有余数+1即可!!!

代码如下:

#include<stdio.h>

int main()
{
    int n,s;
    int num[5] = {0};                   //注意初始化
    int i,cnt = 0;
    scanf("%d",&n);
    for(i = 0 ; i < n ; i++)
    {
        scanf("%d",&s);
        num[s]++;                       //统计小组
    }
    cnt += num[4];                      //人数为4的小组直接算一辆
    if(num[1] > num[3])                 //人数为1的小组比人数为3的小组多
    {
        cnt += num[3]+num[2]/2;
        num[1] -= num[3];
        if(num[2]%2 != 0)
        {
            cnt += 1;
            num[1] -= 2;
        }
        if(num[1] > 0)
        {
            cnt += num[1]/4;
            if(num[1]%4 != 0)
                cnt += 1;
        }
    }
    else                                //人数为1的小组比人数为3的小组少
    {
        cnt += num[3]+num[2]/2;
        if(num[2]%2 != 0)
            cnt += 1;
    }
    printf("%d\n",cnt);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/shuati2000/article/details/100122639