[BZOJ2120]数颜色(分块)

题目描述

传送门

题解

同BZOJ2453

代码

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

const int max_n=1e6+5;
const int max_t=360;

int n,m,x,c,l,r,t1,t2,ans;
int a[max_n],num[max_n],last[max_t],pre[max_n],next[max_n],la[max_n];
int spre[max_n];

inline int in(){
    int x=0; char ch=getchar();
    while (ch<'0'||ch>'9') ch=getchar();
    while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x;
}

inline void change(int x,int c){
    a[x]=c;
    pre[next[x]]=pre[x];
    next[pre[x]]=next[x];
    if (next[x]!=n+1){
        for (int i=last[num[next[x]]-1]+1;i<=last[num[next[x]]];++i)
          spre[i]=pre[i];
        sort(spre+last[num[next[x]]-1]+1,spre+last[num[next[x]]]+1);
    }

    for (int i=x-1;i>=0;--i)
      if (a[i]==c||i==0){
        pre[x]=i,next[i]=x;
        break;
      }
    for (int i=x+1;i<=n+1;++i)
      if (a[i]==c||i==n+1){
        next[x]=i,pre[i]=x;
        break;
      }

    for (int i=last[num[x]-1]+1;i<=last[num[x]];++i)
      spre[i]=pre[i];
    sort(spre+last[num[x]-1]+1,spre+last[num[x]]+1);

    if (next[x]!=n+1&&num[next[x]]!=num[x]){
        for (int i=last[num[next[x]]-1]+1;i<=last[num[next[x]]];++i)
          spre[i]=pre[i];
        sort(spre+last[num[next[x]]-1]+1,spre+last[num[next[x]]]+1);
    }
}

inline void query(int l,int r){
    int lrange,rrange;
    ans=0;
    if (num[l]==num[r]){
        ans=0;
        for (int i=l;i<=r;++i)
          if (pre[i]<l) ++ans;
        printf("%d\n",ans);
        return;
    }

    if (l!=last[num[l]-1]+1){
        lrange=num[l]+1;
        for (int i=l;i<=last[num[l]];++i)
          if (pre[i]<l) ++ans;
    }
    else lrange=num[l];

    if (r!=last[num[r]]){
        rrange=num[r]-1;
        for (int i=last[num[r]-1]+1;i<=r;++i)
          if (pre[i]<l) ++ans;
    }
    else rrange=num[r];

    for (int i=lrange;i<=rrange;++i){
        int loc=lower_bound(spre+last[i-1]+1,spre+last[i]+1,l)-spre-1;
        ans+=loc-(last[i-1]+1)+1;
    }
    printf("%d\n",ans);
}

int main(){
    n=in(); m=in();
    for (int i=1;i<=n;++i) a[i]=in();

    t1=(int)sqrt(n);
    if (n%t1) t2=n/t1+1;
    else t2=n/t1;
    for (int i=1;i<=n;++i)
      num[i]=(i-1)/t1+1;
    for (int i=1;i<=t2;++i){
        last[i]=i*t1;
        if (last[i]>n) last[i]=n;
    }
    for (int i=1;i<=n;++i) next[i]=n+1;
    for (int i=1;i<=n;++i){
        pre[i]=la[a[i]];
        next[la[a[i]]]=i;
        la[a[i]]=i;
        spre[i]=pre[i];
    }
    for (int i=1;i<=t2;++i)
      sort(spre+last[i-1]+1,spre+last[i]+1);

    for (int i=1;i<=m;++i){
        char opt=getchar();
        while (opt!='Q'&&opt!='R') opt=getchar();

        if (opt=='R'){
            x=in(); c=in();
            change(x,c);
        }
        else{
            l=in(); r=in();
            if (l>r) swap(l,r);
            query(l,r);
        }
    }
}

你可能感兴趣的:(分块,bzoj)