BZOJ2038【莫队算法】

THE FIRST 莫队算法。

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL>PII;

const int N=5e4+10;
int n,q;
int a[N];
LL tim[N];

struct asd{
    int Left,Right;
    int id;
    LL res1,res2;
}e[N];
int pos[N];
bool cmp(asd x,asd y){
    if(pos[x.Left]==pos[y.Left]) return x.Right<y.Right;
    return x.Left<y.Left;
}

void solve(){
    LL ans = 0;
    LL res = 0;
    memset(tim,0,sizeof(tim));
    for(int i=0, L=1,R=0;i < q;i++){
        while(R < e[i].Right){
            R++;
            ans = ans + tim[a[R]];
            tim[a[R]]++;
        }
        while(R > e[i].Right){
            tim[a[R]]--;
            ans = ans - tim[a[R]];
            R--;
        }
        while(L > e[i].Left){
            L--;
            ans = ans + tim[a[L]];
            tim[a[L]]++;
        }
        while(L < e[i].Left){
            tim[a[L]]--;
            ans = ans - tim[a[L]];
            L++;
        }
        if(L >= R){
            e[e[i].id].res1=0;
            e[e[i].id].res2=1;
            continue;
        }
        res = (R-L+1LL)*(R-L)/2LL;
        //死wa在了。。。这里,可能0 1的GCD还会有问题。。对啊。。。卧槽!!!
        LL gcd = __gcd(res,ans);
        e[e[i].id].res1 = ans/gcd;
        e[e[i].id].res2 = res/gcd;
    }
}

vector<int>xs;
int main(){
    scanf("%d%d",&n,&q);
    int block=(int)sqrt(n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        pos[i]=(i-1)/block+1;
    }
    for(int i=0;i<q;i++){
        scanf("%d%d",&e[i].Left,&e[i].Right);
        e[i].id = i;
    }
    sort(e,e+q,cmp);

    solve();
    for(int i=0;i<q;i++)
        printf("%lld/%lld\n",e[i].res1,e[i].res2);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值