您的位置:首页 > 其它

Codeforces 158B(贪心问题)

2016-09-21 22:42 387 查看
B. Taxi

time limit per test
3 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output

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 integerss1, 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.

题目大意:
输入一个数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;  
 } 

     
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  贪心