P4135-作诗

题意

\(N\)个数,\(M\)组询问,每次问\([l,r]\)中有多少个数出现正偶数次。

题解:

和上一篇[Violet]蒲公英差不多,都是分块的技巧

预处理(复杂度不能超过操作的复杂度)

预处理出\(s[i][j]\)表示前\(i\)块j出现的次数与\(f[i][j]\)表示第\(i\)块到第\(j\)块的ans

ans初始化为\(f[pl+1][pr-1]\)(\(pr\)\(r\)所在的块,\(pl\)\(l\)所在的块)

然后块外暴力枚举

#include<bits/stdc++.h>
int MIN(int x,int y){return x<=y?x:y;}
#define Fur(i,x,y) for(int i=x;i<=y;i++)
#define clr(x,y) memset(x,y,sizeof(x))
void SWAP(int &x,int &y){x^=y;y^=x;x^=y;}
using namespace std;
#define N 100010
int a[N],n,c,m,L,s[350][N],len,b[N],f[350][350];
int main(){
    ios::sync_with_stdio(false);
    cin>>n>>c>>m;L=sqrt(n);len=(n-1)/L+1;
    Fur(i,1,n)cin>>a[i];
    Fur(i,1,len){
        Fur(j,1,c)s[i][j]=s[i-1][j];
        Fur(j,(i-1)*L+1,i*L)s[i][a[j]]++;
    }
    Fur(i,1,len){
        clr(b,0);int tmp=0;
        Fur(j,i,len){
            Fur(k,(j-1)*L+1,MIN(j*L,n))if(++b[a[k]]!=1)tmp+=((b[a[k]]&1)?-1:1);
            f[i][j]=tmp;
        }
    }
    int l,r,ans=0,pl,pr;
    while(m--){
        cin>>l>>r;l=(l+ans)%n+1;r=(r+ans)%n+1;
        if(l>r)SWAP(l,r);
        pl=(l-1)/L+1;pr=(r-1)/L+1;ans=0;
        if(pr-pl<=2){
            Fur(i,l,r)b[a[i]]=0;
            Fur(i,l,r)if(++b[a[i]]!=1)ans+=((b[a[i]]&1)?-1:1);
        }
        else{
            ans=f[pl+1][pr-1];
            Fur(i,l,MIN(pl*L,n))b[a[i]]=0;
            Fur(i,(pr-1)*L+1,r)b[a[i]]=0;
            Fur(i,l,MIN(pl*L,n)){
                int tmp=++b[a[i]]+s[pr-1][a[i]]-s[pl][a[i]];
                if(tmp!=1)ans+=((tmp&1)?-1:1);
            }
            Fur(i,(pr-1)*L+1,r){
                int tmp=++b[a[i]]+s[pr-1][a[i]]-s[pl][a[i]];
                if(tmp!=1)ans+=((tmp&1)?-1:1);
            }
        }
        cout<<ans<<endl;
    }
}

猜你喜欢

转载自www.cnblogs.com/mimiorz/p/10322329.html
今日推荐