[莫队] 小 Z 的袜子 [国家集训队]

复健一波莫队,发现最经典的模版竟然没做过 \(\\\)

正好复习下这种简单的
P1494

int n,m,ans=0,block;
int col[Max],a[Max];

struct node
{
    int l,r,id;
}q[Max];

struct node1
{
    int x,y;
}res[Max];

int gcd(int a,int b){return b == 0 ? a:gcd(b,a%b);}

bool cmp(node a,node b)
{
    return (a.l/block)^(b.l/block)?(a.l/block)<(b.l/block):(a.l/block)&1?a.r<b.r:a.r>b.r;
}

void add(int x)
{
    ans+=2*col[a[x]]+1;
    col[a[x]]++;
}

void del(int x)
{
    ans+=1-2*col[a[x]];
    col[a[x]]--;
}

signed main()
{
    ios::sync_with_stdio(0);
    cin>>n>>m;
    block=sqrt(n);
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    for(int i=1;i<=m;i++)
    {
        int x,y;
        cin>>q[i].l>>q[i].r;
        q[i].id=i;
    }
    sort(q+1,q+1+m,cmp);
    int l=1,r=0;
    for(int i=1;i<=m;i++)
    {
        int ql=q[i].l,qr=q[i].r;
        while(ql<l) add(--l);
        while(ql>l) del(l++);
        while(qr<r) del(r--);
        while(qr>r) add(++r);
        int len=qr-ql+1;
        if(ans-len==0) {res[q[i].id].x=0,res[q[i].id].y=1;continue;}
        int t=gcd(ans-len,(len-1)*len);
        res[q[i].id].x=(ans-len)/t;
        res[q[i].id].y=(len-1)*len/t;
    }
    for(int i=1;i<=m;i++)
    {
        cout<<res[i].x<<"/"<<res[i].y<<"\n";
    }
    return 0;
}
posted @ 2022-02-20 19:18  juuich  阅读(22)  评论(0编辑  收藏  举报