BZOJ 2038: [2009国家集训队]小Z的袜子(hose) (莫队算法)

原题链接:传送门


Input


输入文件第一行包含两个正整数N和M。N为袜子的数量,M为小Z所提的询问的数量。接下来一行包含N个正整数Ci,其中Ci表示第i只袜子的颜色,相同的颜色用相同的数字表示。再接下来M行,每行两个正整数L,R表示一个询问。

Out


包含M行,对于每个询问在一行中输出分数A/B表示从该询问的区间[L,R]中随机抽出两只袜子颜色相同的概率。若该概率为0则输出0/1,否则输出的A/B必须为最简分数。(详见样例)

Sample Input


6 4
1 2 3 3 3 2
2 6
1 3
3 5
1 6

Sample Output


2/5
0/1
1/1
4/15
「样例解释」
询问1:共C(5,2)=10种可能,其中抽出两个2有1种可能,抽出两个3有3种可能,概率为(1+3)/10=4/10=2/5。
询问2:共C(3,2)=3种可能,无法抽到颜色相同的袜子,概率为0/3=0/1。
询问3:共C(3,2)=3种可能,均为抽出两个3,概率为3/3=1/1。
注:上述C(a, b)表示组合数,组合数C(a, b)等价于在a个不同的物品中选取b个的选取方案数。
「数据规模和约定」
30%的数据中 N,M ≤ 5000;
60%的数据中 N,M ≤ 25000;
100%的数据中 N,M ≤ 50000,1 ≤ L < R ≤ N,Ci ≤ N。


#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
typedef long long ll;
const int N = 5e5+10;
ll col[N],cnt[N],pos[N];
int n,m,block;
ll ans;

struct node {
    ll l,r,id;
    ll A,B;
} a[N];

bool cmp(node a,node b) {
    if(pos[a.l] == pos[b.l])
        return a.r < b.r;
    return a.l < b.l;
}

bool cmp2(node a,node b) {
    return a.id < b.id;
}

ll gcd(ll a,ll b) {
    return b?gcd(b,a%b):a;
}

void init() {
    scanf("%d%d",&n,&m);
    block = sqrt(n);
    for(int i=1; i<=n; i++) {
        scanf("%d",&col[i]);
        pos[i] = (i-1)/block+1; 
    }
    for(int i=1; i<=m; i++) {
        scanf("%d%d",&a[i].l,&a[i].r);   
        a[i].id = i;
    }
}

void updata(int x,int d) {
    ans -= cnt[x] * (cnt[x] - 1);
    cnt[x] += d;
    ans += cnt[x] * (cnt[x] - 1);
}

void solve() {
    int L = 1,R = 0;
    ans = 0;
    for(int i=1; i<=m; i++) {
        while(L < a[i].l)   updata(col[L++],-1);
        while(L > a[i].l)   updata(col[--L],1);
        while(R < a[i].r)   updata(col[++R],1);
        while(R > a[i].r)   updata(col[R--],-1);

        if(a[i].l == a[i].r) {
            a[i].A = 0;
            a[i].B = 1;
            continue;
        }
        a[i].A = ans;
        a[i].B = 1LL*(R-L+1)*(R-L);
        ll G = gcd(a[i].A,a[i].B);
        a[i].A /= G;
        a[i].B /= G;
    }
}

int main() {
    init();
    sort(a+1,a+m+1,cmp);
    solve();

//  for(int i=1;i<=m;i++){
//      ll G = gcd(a[i].A,a[i].B);
//      a[i].A /= G;
//      a[i].B /= G;
//      if(!a[i].A) a[i].B = 1;
//  }
    sort(a+1,a+m+1,cmp2);
    for(int i=1; i<=m; i++) {
        printf("%lld/%lld\n",a[i].A,a[i].B);
    }

    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_16554583/article/details/81170872