题目描述: B. 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
- 题意:有N个组,每组不超过4个人,不少于1个人。现在有出租车,一辆最多拉4个人,一个组的 人必须坐在一辆 出租车上。不同的组可以拼车。问最少几辆车就可以全部拉上?
- 思路:很自然就可以想到4人一组就坐一辆车。3人一组可以和一人一组一起拼车。2人一组可以和2人一组的拼车,也可以和一人一组的拼车,一人一组可以和3人,2人,1人的拼车。
- 贪心:根据要求最少车辆,那么可知4人的肯定占一辆,3人的占一辆,但会有一个空位,可以把单人的补进来,对于2个人的先补2人的,如果多出来就再补1人的,这里要注意,2人的可以补2个1人的。剩下的就是1人的了,这里也要注意。1个人一组的可以互相拼,就是说4个一人一组的可以拼一个车。
这里是代码
# include <stdio.h>
int main()
{
int arr[100001];
int n;
int k = 0;
int k4 = 0,k3 = 0,k2 = 0,k1 = 0; //记录不同人数组的数量
scanf("%d",&n);
for(int i = 0;i < n; i++) // 录入数据
{
scanf("%d",&arr[i]);
}
for (int i = 0;i < n;i++) // 4人一组的数量
{
if(arr[i] == 4)
{
k4++;
arr[i] = -1;
}
}
for (int i = 0;i < n;i++) // 3人一组的数量
{
if(arr[i] == 3)
{
arr[i] = -1;
k3++;
}
}
for (int i = 0;i<n;i++) // 俩人一组的数量
{
if(arr[i] == 2)
{
arr[i] = -1;
k2++;
}
}
k1 = n - k4 -k3 -k2; //单人的
k = k4 + k3 + k2/2;
if(k1 > k3) // 判断一人一组的数量和三人一组的数量
k1 = k1 - k3; // 如果一人一组的少于3人一组的k1 = 0;
else
k1 = 0;
k2 = k2%2; //2人一组的互相匹配,看是否会剩下一组2人的
if(k2 == 1)
{
k++;
if(k1 > 2) //因为2人一组的可以和2个一人一组的拼车,所以减去俩个k1
{
k1 = k1 -2;
}
else
k1 = 0;
}
k = k + k1 / 4;
if((k1 % 4) != 0)
k++;
printf("%d\n",k);
return 0;
}