作为一个生活散漫的人,小Z每天早上都要耗费很久从一堆五颜六色的袜子中找出一双来穿。终于有一天,小Z再也无法忍受这恼人的找袜子过程,于是他决定听天由命…… 具体来说,小Z把这N只袜子从1到N编号,然后从编号L到R(L
包含M行,对于每个询问在一行中输出分数A/B表示从该询问的区间[L,R]中随机抽出两只袜子颜色相同的概率。若该概率为0则输出0/1,否则输出的A/B必须为最简分数。
莫队算法可以解决一类不修改、离线查询问题。
把1~n分成sqrt(n)段。
unit = sqrt(n)
m个查询先按照第几个块排序,再按照 R排序。
然后直接求解。
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
const int MAXN = 50010;
const int MAXM = 50010;
struct Query
{
int L,R,id;
}node[MAXM];
long long gcd(long long a,long long b)
{
if(b == 0)return a;
return gcd(b,a%b);
}
struct Ans
{
long long a,b;//分数a/b
void reduce()//分数化简
{
long long d = gcd(a,b);
a /= d; b /= d;
}
}ans[MAXM];
int a[MAXN];
int num[MAXN];
int n,m,unit;
bool cmp(Query a,Query b)
{
if(a.L/unit != b.L/unit)return a.L/unit < b.L/unit;
else return a.R < b.R;
}
void work()
{
long long temp = 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++;
temp -= (long long)num[a[R]]*num[a[R]];
num[a[R]]++;
temp += (long long)num[a[R]]*num[a[R]];
}
while(R > node[i].R)
{
temp -= (long long)num[a[R]]*num[a[R]];
num[a[R]]--;
temp += (long long)num[a[R]]*num[a[R]];
R--;
}
while(L < node[i].L)
{
temp -= (long long)num[a[L]]*num[a[L]];
num[a[L]]--;
temp += (long long)num[a[L]]*num[a[L]];
L++;
}
while(L > node[i].L)
{
L--;
temp -= (long long)num[a[L]]*num[a[L]];
num[a[L]]++;
temp += (long long)num[a[L]]*num[a[L]];
}
ans[node[i].id].a = temp - (R-L+1);
ans[node[i].id].b = (long long)(R-L+1)*(R-L);
ans[node[i].id].reduce();
}
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(scanf("%d%d",&n,&m) == 2)
{
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);
}
unit = (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;
}