NowCoder HNNU Competition J

https://www.nowcoder.com/acm/contest/127/J

A problem of Mo's Algorithm

这题就是为莫队出的

除了莫队别的我也想不出啥了

WildCow mentor and dragon teammate give me the algorithm

Amazing

莫队算法真是太神了

写法简单

变化多样

只要不是强制在线

几乎是处理区间处理的万能方法

这题首先用筛选法把每个数像拔鸡毛一样拔干净了

然后剩下的就是特征值了

之后加减值直接在特征值上处理

莫队真的是一个既神奇又不要脸的大怪物

我好喜欢这个怪物

还有明天WildCow学长打在徐州邀请赛

祝他顺利

#include<bits/stdc++.h>
using namespace std;
const int N=1e6;
int l,r,Ans,zero,pos[N],ans[N],A[N],P[N+10],cnt1[N],cnt2[N];
struct Quary{
    int l,r,num;
}quary[N];
bool cmp(Quary a,Quary b){
    if(pos[a.l]==pos[b.l]) return a.r < b.r;
    else return pos[a.l] < pos[b.l];
}
void pre(){
    for(int i=1;i<=N;++i) P[i]=i;
    for(int i=2;i<=N;++i){
        if(P[i]==i){
            for(int j=2*i;j<=N;j+=i){
                while(P[j]%(i*i)==0) P[j]/=i*i;
            }
        }
    }
}
int cul(int x){
    return x*(x-1)/2;
}
void Add(int x){
    if(A[x]==0){
        ++zero;
    }else if(A[x]>0){
        Ans-=cul(cnt1[P[A[x]]]);
        ++cnt1[P[A[x]]];
        Ans+=cul(cnt1[P[A[x]]]);
    }else{
        Ans-=cul(cnt2[P[-A[x]]]);
        ++cnt2[P[-A[x]]];
        Ans+=cul(cnt2[P[-A[x]]]);
    }
}
void Del(int x){
    if(A[x]==0){
        --zero;
    }else if(A[x]>0){
        Ans-=cul(cnt1[P[A[x]]]);
        --cnt1[P[A[x]]];
        Ans+=cul(cnt1[P[A[x]]]);
    }else{
        Ans-=cul(cnt2[P[-A[x]]]);
        --cnt2[P[-A[x]]];
        Ans+=cul(cnt2[P[-A[x]]]);
    }
}
int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    pre();
    int n,m;
    cin>>n;
    int block=sqrt(n);
    for(int i=1;i<=n;++i) cin>>A[i],pos[i]=i/block;
    cin>>m;
    for(int i=1;i<=m;++i) cin>>quary[i].l>>quary[i].r,quary[i].num = i;
    sort(quary+1,quary+m+1,cmp);
    l=1,r=0;
    for(int i=1;i<=m;++i){
        while(l<quary[i].l) Del(l),++l;
        while(l>quary[i].l) --l,Add(l);
        while(r<quary[i].r) ++r,Add(r);
        while(r>quary[i].r) Del(r),--r;
        ans[quary[i].num]=Ans+(r-l+1-zero)*zero+cul(zero);
    }
    for(int i=1;i<=m;++i) printf("%d\n",ans[i]);
}

Code of AC


猜你喜欢

转载自blog.csdn.net/gipsy_danger/article/details/80551830