莫队算法 小Z的袜子



#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<cmath>
#include<string>
#include<algorithm>
#include<set>
#include<map>
#include<cstring>
#include<queue>
#include<stack>
#include<list>

using namespace std;

typedef long long ll;
const int MAXN=50010;

struct Query{
    int L,R,id;
}node[MAXN];

ll gcd(ll a,ll b){
    if(b==0)return a;
    return gcd(b,a%b);
}

struct Ans{
    ll a,b;
    void reduce(){
        ll d=gcd(a,b);
        a/=d;b/=d;
    }
}ans[MAXN];

int a[MAXN];
int num[MAXN];
int n,m,unite;

bool cmp( Query a,Query b ){
    if(a.L/unite==b.L/unite)return a.R<b.R;
    return a.L/unite<b.L/unite;
}

ll pow2(ll x){
    return x*x;
}

void work(){
    ll tmp=0;
    memset(num,0,sizeof(num));
    int L=1;
    int R=0;
    for(int i=0;i<m;i++){
        while( R<node[i].R ){
            R++;
            tmp-= pow2( num[a[R]] );
            num[ a[R] ]++;
            tmp+= pow2( num[a[R]] );
        }
        while( R>node[i].R ){
            tmp-= pow2( num[a[R]] );
            num[ a[R] ]--;
            tmp+= pow2( num[a[R]] );
            R--;
        }
        while( L<node[i].L ){
            tmp-= pow2( num[a[L]] );
            num[ a[L] ]--;
            tmp+= pow2( num[a[L]] );
            L++;
        }
        while( L>node[i].L ){
            L--;
            tmp-= pow2( num[a[L]] );
            num[ a[L] ]++;
            tmp+= pow2( num[a[L]] );
        }
        ans[ node[i].id ].a=tmp-(R-L+1);
        ans[ node[i].id ].b=(ll) (R-L+1)*(R-L);
        ans[ node[i].id ].reduce();

    }

}

int main()
{
    while(scanf("%d%d",&n,&m)!=EOF){
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
        }
        for(int i=0;i<m;i++){
            node[i].id=i;
            scanf("%d%d",&node[i].L,&node[i].R);
        }
        unite=(int ) sqrt(n);
        sort( node,node+m,cmp );
        work();
        for(int i=0;i<m;i++){
            printf("%lld/%lld\n",ans[i].a,ans[i].b);
        }

    }


	return 0;
}













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值