B. Taxi (貪心)

原題鏈接

158B

題目描述

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.

inputCopy
5
1 2 4 3 3
outputCopy
4
inputCopy
8
2 3 4 4 2 1 3 1
outputCopy
5

思路

一道貪心的題目,剛開始看錯了題,後來才發現一輛車必須載整個組的人。由於每組人數至多4人,所以我們可以維護一個cnt數組,記錄每組人數的數量。題目要求求出最少的車輛,我們的策略就是:四人組的無法與其他組同坐,三人組的可以與一人組同坐,二人組可以和二人組同坐,四個一人組可以在一起,做完這些後再處理剩餘的二人組和一人組,每個二人組可以與兩個人一組同坐,最後再處理一遍一人組即可。

AC代碼

#include<bits/stdc++.h>
#define x first
#define y second
#pragma GCC optimize(2)
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC optimize(3)
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC target("sse3","sse2","sse")
#pragma GCC target("avx","sse4","sse4.1","sse4.2","ssse3")
#pragma GCC target("f16c")
#pragma GCC optimize("inline","fast-math","unroll-loops","no-stack-protector")
#pragma GCC diagnostic error "-fwhole-program"
#pragma GCC diagnostic error "-fcse-skip-blocks"
#pragma GCC diagnostic error "-funsafe-loop-optimizations"
#pragma GCC diagnostic error "-std=c++14"
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef long long LL;
const int N=1e5+10;
const int INF=0x3f3f3f3f;
const int MOD=998244353;
int n;
int a[N];
int cnt[5];
int main(){
	IOS;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
        cnt[a[i]]++;
    }
    int ans=0;
    ans+=cnt[4];
    ans+=cnt[3];
    cnt[1]-=cnt[3];
    if(cnt[1]<=0) ans+=cnt[2]/2+cnt[2]%2;
    else{
        ans+=cnt[1]/4;
        cnt[1]-=cnt[1]/4*4;
        ans+=cnt[2]/2;
        cnt[2]-=cnt[2]/2*2;
        ans+=cnt[2];
        cnt[1]-=cnt[2]*2;
        if(cnt[1]>0) ans+=1;
    }
    cout<<ans<<endl;
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章