洛谷 P1494 - 小z的袜子(莫队算法)

题目描述

作为一个生活散漫的人,小Z每天早上都要耗费很久从一堆五颜六色的袜子中找出一双来穿。终于有一天,小Z再也无法忍受这恼人的找袜子过程,于是他决定听天由命……

具体来说,小Z把这N只袜子从1到N编号,然后从编号L到R(L 尽管小Z并不在意两只袜子是不是完整的一双,甚至不在意两只袜子是否一左一右,他却很在意袜子的颜色,毕竟穿两只不同色的袜子会很尴尬。

你的任务便是告诉小Z,他有多大的概率抽到两只颜色相同的袜子。当然,小Z希望这个概率尽量高,所以他可能会询问多个(L,R)以方便自己选择。

然而数据中有L=R的情况,请特判这种情况,输出0/1。

输入输出格式

输入格式:

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

输出格式:

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

输入输出样例

输入样例#1: 

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

输出样例#1: 

2/5
0/1
1/1
4/15

说明

30%的数据中 N,M ≤ 5000;

60%的数据中 N,M ≤ 25000;

100%的数据中 N,M ≤ 50000,1 ≤ L < R ≤ N,Ci ≤ N。

#include<bits/stdc++.h>
using namespace std;
#define LL long long

const int N = 50005;

int n,m,c[N];
LL s[N],ans;
struct node{
    int l,r,id;
    int pos;
    LL a,b;
}p[N];
LL gcd(LL x,LL y){return !y?x:gcd(y,x%y);}
bool cmp(node a,node b){
    if(a.pos == b.pos )
        return a.r < b.r;
    return a.pos < b.pos;
}
bool cmp_id(node a,node b){
    return a.id < b.id;
}
void update(int p,int add){
    ans -= s[c[p]]*s[c[p]];
    s[c[p]] += add;
    ans += s[c[p]]*s[c[p]];
}
void solve(){
    for(int i=1,l=1,r=0;i<=m;i++){
        while(r < p[i].r){update(r+1,1);r++;}
        while(r > p[i].r){update(r,-1);r--;}
        while(l < p[i].l){update(l,-1);l++;}
        while(l > p[i].l){update(l-1,1);l--;}
        if(p[i].l == p[i].r){
            p[i].a = 0;
            p[i].b = 1;
            continue;
        }
        p[i].a = ans - (p[i].r - p[i].l + 1);
        p[i].b = (p[i].r - p[i].l + 1) * 1LL * (p[i].r - p[i].l);
        LL g = gcd(p[i].a,p[i].b);
        p[i].a /= g;
        p[i].b /= g;
    }
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        scanf("%d",&c[i]);
    int len = sqrt(n);
    for(int i=1;i<=m;i++){
        scanf("%d%d",&p[i].l,&p[i].r);
        p[i].id = i;
        p[i].pos = p[i].l / len;
    }
    sort(p+1,p+m+1,cmp);
    solve();
    sort(p+1,p+m+1,cmp_id);
    for(int i=1;i<=m;i++)
        printf("%lld/%lld\n",p[i].a,p[i].b);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/l18339702017/article/details/81485886