[BZOJ3585]mex(离线+离散化+线段树)

题目描述

传送门

题解

和BZOJ3339基本一样。但是需要离散化求next,然后求sg我用了map。

代码

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<map>
using namespace std;

const int max_n=2e5+5;
const int max_tree=max_n*4;
const int INF=2e9;

int n,m,cnt,k,L,a[max_n],b[max_n],p[max_n],sg[max_n],next[max_n],last[max_n];
struct hp{int l,r,id,ans;}q[max_n];
int tree[max_tree],delta[max_tree];
map <int,bool>mark;

inline int cmp1(int x,int y){return a[x]<a[y];}
inline int cmp(hp a,hp b){return a.l<b.l;}
inline void update(int now){tree[now]=min(tree[now<<1],tree[now<<1|1]);}
inline void pushdown(int now,int l,int r,int mid){
    if (delta[now]!=INF){
        tree[now<<1]=min(tree[now<<1],delta[now]);
        delta[now<<1]=min(delta[now<<1],delta[now]);
        tree[now<<1|1]=min(tree[now<<1|1],delta[now]);
        delta[now<<1|1]=min(delta[now<<1|1],delta[now]);
        delta[now]=INF;
    }
}
inline void build(int now,int l,int r){
    int mid=(l+r)>>1;delta[now]=INF,tree[now]=INF;
    if (l==r){
        tree[now]=sg[l];
        return;
    }
    build(now<<1,l,mid);
    build(now<<1|1,mid+1,r);
    update(now);
}
inline void interval_change(int now,int l,int r,int lrange,int rrange,int v){
    int mid=(l+r)>>1;
    if (lrange<=l&&r<=rrange){
        tree[now]=min(tree[now],v);
        delta[now]=min(delta[now],v);
        return;
    }
    pushdown(now,l,r,mid);
    if (lrange<=mid) interval_change(now<<1,l,mid,lrange,rrange,v);
    if (mid+1<=rrange) interval_change(now<<1|1,mid+1,r,lrange,rrange,v);
    update(now);
}
inline int query(int now,int l,int r,int x){
    int mid=(l+r)>>1;
    if (l==r) return tree[now];
    pushdown(now,l,r,mid);
    if (x<=mid) return query(now<<1,l,mid,x);
    else return query(now<<1|1,mid+1,r,x);
}
int main(){
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;++i) scanf("%d",&a[i]),p[i]=i;
    sort(p+1,p+n+1,cmp1);
    for (int i=1;i<=n;++i)
      if (a[p[i]]==a[p[i-1]]) b[p[i]]=cnt;
      else b[p[i]]=++cnt;
    k=0;
    for (int i=1;i<=n;++i){
        mark[a[i]]=1;
        while (mark[k]) k++;
        sg[i]=k;
    }
    for (int i=1;i<=n;++i) next[i]=n+1;
    for (int i=1;i<=n;++i){
        next[last[b[i]]]=i;
        last[b[i]]=i;
    }
    build(1,1,n);
    for (int i=1;i<=m;++i)
      scanf("%d%d",&q[i].l,&q[i].r),q[i].id=i;
    sort(q+1,q+m+1,cmp);
    L=1;
    for (int i=1;i<=m;++i){
        while (L<q[i].l){
            interval_change(1,1,n,L,next[L]-1,a[L]);
            L++;
        }
        q[q[i].id].ans=query(1,1,n,q[i].r);
    }
    for (int i=1;i<=m;++i)
      printf("%d\n",q[i].ans);
}

你可能感兴趣的:(线段树,bzoj)