题解:CF2146E Yet Another MEX Problem

· · 题解

好久没写线段树了。


#include<bits/stdc++.h>
using namespace std;
const int N = 3e5 + 7;
int n,m;
int tr[N*4],tag[N*4];
void pushdown(int x){
    tag[x*2] += tag[x];
    tag[x*2+1] += tag[x];
    tr[x*2] += tag[x];
    tr[x*2+1] += tag[x];
    tag[x] = 0;
}
void build(int x,int l,int r){
    tr[x] = tag[x] = 0;
    if(l==r){
        return;
    }
    int mid = (l+r)/2;
    build(x*2,l,mid);
    build(x*2+1,mid+1,r);
    tr[x] = max(tr[x*2],tr[x*2+1]);
}
void update(int x,int l,int r,int L,int R){
    if(L>r || l>R) return;
    if(l<=L && R<=r){
        tr[x] += 1;
        tag[x] += 1;
        return;
    }
    pushdown(x);
    int mid = (L+R)/2;
    update(x*2,l,r,L,mid);
    update(x*2+1,l,r,mid+1,R);
    tr[x] = max(tr[x*2],tr[x*2+1]);
}
void mdf(int x,int l,int r,int pos){
    if(l==r){
        tr[x] = 0;
        return;
    }
    pushdown(x);
    int mid = (l+r)/2;
    if(pos<=mid) mdf(x*2,l,mid,pos);
    else mdf(x*2+1,mid+1,r,pos);
    tr[x] = max(tr[x*2],tr[x*2+1]);
}
void solve(){
    cin>>n;
    build(1,0,n);
    for(int i=1;i<=n;++i){
        int x;cin>>x;
        update(1,0,x-1,0,n);
        mdf(1,0,n,x);
        cout<<tr[1]<<' ';
    }
    cout<<'\n';
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int T;cin>>T;
    for(int _=1;_<=T;++_){
        solve();
    }
    return 0;
}