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)?
The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integerss1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group.
Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus.
5 1 2 4 3 3
4
8 2 3 4 4 2 1 3 1
5
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.
题目大意:
输入一个数n表示有n个小组,第二行表示n个小组各自的人数(人数不大于4)。每辆出租车最多可以乘坐4人,求要n各小组的人都坐上出租车,且所需出租车的最少数量是多少。
解题思路:
共有五种打车的方法:
4人一车;2+2人一车;3+1人一车;2+1+1人一车;1+1+1+1人一车。(为了简单起见,先用sort函数按从大到小排序,也可以不用)很容易想到我们应该要将小数加到大数上,尽可能的凑到4。这里用到了贪心算法,一个数想要加到4,并且使要加的组数最大,那么尽可能的加一些小一点的数,是最好的。比如2要加到4,肯定2+1+1比2+2要好。
代码实现:
- #include<cstdio>
- #include<iostream>
- #include<algorithm>
- #include<cstring>
- using namespace std;
- int a[5];
- int main()
- {
-
- int i,n,x,sum;
- while(~scanf("%d",&n))
- {
- memset(a,0,sizeof(a));
- sum=0;
- for(i=0; i<n; i++)
- {
- scanf("%d",&x);
- a[x]++;
- }
- sum+=a[4]+a[3];
- x=a[1]-a[3];
- if(a[2]%2==0)
- sum+=a[2]/2;
- else
- {
- sum+=(a[2]+1)/2;
- x-=2;
- }
- if(x>0)
- {
- sum+=x/4;
- x=x%4;
- if(x)
- sum++;
- }
- printf("%d\n",sum);
- }
- return 0;
- }
本文介绍了一种算法问题,即如何计算最少数量的出租车来运送分成不同大小群体的孩子们,确保每个群体都乘坐同一辆车。文章提供了问题描述、示例输入输出及一种可行的解决方案。

被折叠的 条评论
为什么被折叠?



