P4137 Rmq Problem / mex

· · 题解

求 mex 的一种暴力方法,用 bitset 数组维护当前区间存在值,用 _Find_first() 找到最小的不存在的正整数

#include<bits/stdc++.h>
using namespace std;
struct node{
    int l,r,id;
}q[200001];
int n,m,l,r,sq;
int a[200001],d[200001],num[200001],ans[200001];
bitset<200002> b;
inline int read()
{
    int x(0);char ch(getchar());
    while(ch<48||ch>57) ch=getchar();
    while(ch>=48&&ch<=57) x=x*10+(ch^48),ch=getchar();
    return x;
}
bool cmp(node x,node y)
{
    return d[x.l]<d[y.l]||d[x.l]==d[y.l]&&(d[x.l]&1?x.r<y.r:x.r>y.r);
}
void add(int x)
{
    if(!num[a[x]]) b.set(a[x]);
    num[a[x]]++;
}
void del(int x)
{
    num[a[x]]--;
    if(!num[a[x]]) b.reset(a[x]);
}
int main()
{
//  freopen("P4137.in","r",stdin);
//  freopen("P4137.out","w",stdout);
    n=read(),m=read();sq=sqrt(n);
    for(int i=1;i<=n;i++) a[i]=read(),d[i]=(i-1)/sq+1;
    for(int i=1;i<=m;i++)
        q[i].l=read(),q[i].r=read(),q[i].id=i;
    sort(q+1,q+1+m,cmp);
    l=1,r=0;
    for(int i=1;i<=m;i++)
    {
        while(l<q[i].l) del(l++);
        while(l>q[i].l) add(--l);
        while(r<q[i].r) add(++r);
        while(r>q[i].r) del(r--);
        ans[q[i].id]=(~b)._Find_first();
    }
    for(int i=1;i<=m;i++) printf("%d\n",ans[i]);
    return 0;
}