线段树二分&MEX

· · 个人记录

线段树二分&MEX

Mex and Update - AtCoder abc330_e - Virtual Judge

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll maxn=2e6+5;

const ll lmt=1e9;
ll n;
struct nd {
    ll sum,lazy;
    ll L,R;
    nd() {sum=0;lazy=-1;L=R=0;}
};
nd operator + (const nd &a,const nd &b) {
    nd res;
    res.sum=a.sum+b.sum;
    return res;
}
template <typename T>
struct SegmentTree {
    ll n,cur=1,t;
    vector<T> f;
    SegmentTree (ll _n) {
        n=_n;
        f.resize(n<<2,T());
    }
    T merge (T x,T y) {return x+y;}
    void update(ll now,ll l,ll r,ll val) {
        f[now].sum=(r-l+1)*val;
        f[now].lazy=val;
    }
    void push_down(ll now,ll l,ll r) {
        if (f[now].lazy==-1||l==r) return ;
        ll mid=l+r>>1;
        update(now<<1,l,mid,f[now].lazy);
        update(now<<1|1,mid+1,r,f[now].lazy);
        f[now].lazy=-1;
    }
    void push_up(ll now) {
        f[now].sum=f[now<<1].sum+f[now<<1|1].sum;
    }
    T query(ll now,ll l,ll r,ll x,ll y) {
        if (r<x||y<l) return T();
        if (x<=l&&r<=y) return f[now];
        push_down(now,l,r);
        ll mid=l+r>>1;
        return merge(query(now<<1,l,mid,x,y),query(now<<1|1,mid+1,r,x,y));
    }
    ll ask(ll now,ll l,ll r) {
        if (f[now].sum==r-l+1) return n+1;
        if (l==r) return l;
        push_down(now,l,r);
        ll mid=l+r>>1;
        if (f[now<<1].sum<mid-l+1) return ask(now<<1,l,mid);
        else return ask(now<<1|1,mid+1,r);
    }
    void modify(ll now,ll l,ll r,ll x,ll y,ll val) {
        if (l>y||r<x) return ;
        if (x<=l&&r<=y) {
            update(now,l,r,val);
            return ;
        }
        push_down(now,l,r);
        ll mid=l+r>>1;
        modify(now<<1,l,mid,x,y,val);
        modify(now<<1|1,mid+1,r,x,y,val);
        push_up(now);
    }
    T Query(ll l,ll r) {return query(1,1,n,l,r);}
    void Modify(ll l,ll r,ll val) {modify(1,1,n,l,r,val);}
};
int a[maxn];
int cnt[maxn];
void solve() {
    ll n,q;
    cin>>n>>q;
    for (int i=0;i<=n;i++) cnt[i]=0;
    SegmentTree<nd> seg(n);
    for (int i=1;i<=n;i++) {
        cin>>a[i];a[i]++;
        if (a[i]<=n) seg.Modify(a[i],a[i],1),cnt[a[i]]++;
    }
    while (q--) {
        int id,nxt;cin>>id>>nxt;
        nxt++;
        int lst=a[id];
        a[id]=nxt;
        if (lst<=n) {
            cnt[lst]--;
            if (!cnt[lst]) seg.Modify(lst,lst,0);
        }
        if (nxt<=n) {
            if (!cnt[nxt]) seg.Modify(nxt,nxt,1);
            cnt[nxt]++;
        }
        cout<<seg.ask(1,1,n)-1<<endl;
    }

}

int main() {
    ios::sync_with_stdio(0);
    int t=1;
//    cin>>t;
    while (t--) solve();

}