J - 马老师的餐厅
题目大意
给出 n n n个数,要求每次取出互不相同的三个数,组成一组,问最多能取出多少组。
题解
运用贪心思想,每次取一定是取剩余数量最多的三个数。
这个可以用优先队列来维护,
每次取出队列头的三个数,组成一组,然后把它们的剩余数量 − 1 -1 −1,再仍会队列里。
时间复杂度
优先队列单词操作的时间复杂度 O ( l o g n ) O(log_n) O(logn),总共由 n n n个数,于是总的时间复杂度就是 O ( n × l o g n ) O(n\times log_n) O(n×logn)
Tag
优先队列
贪心算法
code
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
#include <queue>
#define G getchar
using namespace std;
int read()
{
char ch;
for(ch=G();ch<'0' || ch>'9';ch=G());
int n=0;
for(;'0'<=ch && ch<='9';ch=G())n=(n<<1)+(n<<3)+ch-48;
return n;
}
const int N=100005;
int n;
int ans,m;
int a[N],opx,sum[N];
struct node
{
int x,s;
bool operator <(const node &n)const
{
return s<n.s;
}
};
node mx1[N<<2],mx2[N<<2],mx3[N<<2];
priority_queue<node> q;
void mix(int x)
{
while(!q.empty())q.pop();
int ls=x<<1,rs=ls|1;
q.push(mx1[ls]);
q.push(mx2[ls]);
q.push(mx3[ls]);
q.push(mx1[rs]);
q.push(mx2[rs]);
q.push(mx3[rs]);
mx1[x]=q.top();
q.pop();
mx2[x]=q.top();
q.pop();
mx3[x]=q.top();
q.pop();
}
void build(int x,int l,int r)
{
if(l==r)
{
mx1[x].x=l;
mx1[x].s=sum[l];
return;
}
int m=(l+r)>>1;
build(x<<1,l,m);
build((x<<1)|1,m+1,r);
mix(x);
}
void work(int x,int l,int r)
{
if(l==r)
{
mx1[x].s--;
if(mx1[x].s==0)mx1[x].x=0;
return;
}
int m=(l+r)>>1;
if(opx<=m)work(x<<1,l,m);else work((x<<1)|1,m+1,r);
mix(x);
}
int main()
{
//freopen("j.in","r",stdin);
//freopen("j.out","w",stdout);
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
sort(a+1,a+1+n);
a[m=0]=a[1]-1;
for(int i=1;i<=n;i++)
if(a[i]^a[i-1])sum[++m]++;else sum[m]++;
build(1,1,m);
for(;mx3[1].x;)
{
ans++;
opx=mx3[1].x;
work(1,1,m);
opx=mx2[1].x;
work(1,1,m);
opx=mx1[1].x;
work(1,1,m);
}
printf("%lld",ans);
}