题意:有N(1 ≤ n ≤ 10^5)个组,输入Si(1<= Si <= 4),Si代表第i组有Si个人。现在要求将所有人都能运走,问需要多少辆出租车,已知一辆出租车最多能装4人,一个组的人不能分开坐,同时一辆出租车可以装不同组的人。
分析:很明显的贪心,先满足人多的组,人数不够的拿人数少的组中凑。
①先将人数从小到大排序,设两个指针s,e分别指向头尾
②若a[e] == 4则出租车数量+1 e–,若a[e] < 4 则 a[e]就要不断从a[s],s++;中凑人数,直到凑满或没得凑为止 e–;。
③当s >= e 结束
具体代码:
const double EPS = 1e-6;
const int maxn = 100000 + 10;
const int INF = (1 << 30);
int a[maxn];
int main(){
int n;
cin >> n;
int s = 0, e = n-1;
for(int i = 0; i < n; ++i)
cin >> a[i];
sort(a,a+n);
int ans = 0;
for(int i = e; i >= s; i--){
if(a[i] < 4){
int tmp = a[i];
while(tmp + a[s] <= 4 && s != i){
tmp += a[s];
s++;
}
ans++;
}
else ans++;
}
cout << ans << endl;
return 0;
}
头文件:
#include <set>
#include <numeric>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cctype>
#include <string>
#include <sstream>
#include <map>
#include <functional>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
#define REP(idx1,num1) for(LL idx1=0;idx1<(num1);idx1++)
#define pb push_back
#define empb emplace_back
#define mk make_pair
#define mem(s) memset(s,0,sizeof(s));