158B_Taxi : Codeforces

158B_Taxi : Codeforces

Difficulty: 1100 | C++

special problem, greedy, implementation

View Question on codeforces

Problem Statement

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 1

5
1 2 4 3 3

Output 1


4

Input 2

8
2 3 4 4 2 1 3 1

Output 2

5

It is appreciated if have already tried it before checking the solution.

Solution

My solution has a time complexity if O(n)

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    vector<int> a(n);
    map<int , int> m;
    for(int i=0;i<n;i++)
    {
        cin>>a[i];
        m[a[i]]++;
    }
    int ans =0;
    if(m[4] > 0){
        ans += m[4];
        m[4] = 0;
    }
    if(m[3] > 0){
        if(m[1] >= m[3]){
            ans += m[3];
            m[1] = m[1] - m[3];
        }
        else{
            ans += m[1];
            m[3] -= m[1];
            ans += m[3];
            m[1] = 0;
        }
        m[3] = 0;
    }
    if(m[2] > 0){
        ans += m[2] /2;
        int temp = m[2]%2;
        if(temp){
            if(m[1] > 1){
                m[1] -= 2;
                m[2] =0;
            }else if(m[1] == 1){
                m[1] =0;
                m[2] =0;
            }else{
                m[2] =0;
            }
            ans += 1;
        }
    }
    if(m[1] > 0){
        ans += m[1]/4;
        int x = m[1]%4;
        if(x){
            ans+=1;
        }
    }
    cout<<ans<<endl;

    return 0;
}

I you have a better answer please share that in the comment I will change it from my answer.

Did you find this article valuable?

Support Rohit Gupta by becoming a sponsor. Any amount is appreciated!