# 小Z的袜子【莫队算法】

[2009国家集训队]小Z的袜子(hose)

Time Limit: 20 Sec Memory Limit: 259 MB
Submit: 5259 Solved: 2426
[Submit][Status][Discuss]
Description

Input

Output

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

【样例解释】

【数据规模和约定】

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

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

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

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>

using namespace std;

int c[50010], pos[50010];;
int n, m;
long long ans, aa, bb, cc, s[50010];

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

struct Query
{
int L, R;
int num;

long long ans1, ans2;

}q[50010];

bool cmp1(Query a, Query b)
{
if (pos[a.L] == pos[b.L])
return a.R < b.R;
else
return a.L < b.L;
}

bool cmp2(Query a, Query b)
{
return a.num < b.num;
}

{
ans -= s[c[p]] * s[c[p]];
ans += s[c[p]] * s[c[p]];
}

int main()
{
while (scanf("%d%d", &n, &m) != EOF)
{
int SQ = sqrt(n);
ans = 0;
memset(s, 0, sizeof(s));

for (int i = 1;i <= n;i++)
{
scanf("%d", &c[i]);
pos[i] = (i - 1) / SQ + 1;
}

for (int i = 1;i <= m;i++)
{
scanf("%d%d", &q[i].L, &q[i].R);
q[i].num = i;
}

sort(q + 1, q + 1 + m,cmp1);

int pl = 1, pr = 0;

for (int i = 1;i <= m;i++)
{
if (q[i].L == q[i].R)
{
q[i].ans1 = 0;
q[i].ans2 = 1;
continue;
}

if (pr < q[i].R)
{
for (int j = pr + 1;j <= q[i].R;j++)
update(j, 1);
}
else
{
for (int j = pr ;j > q[i].R;j--)
update(j, -1);
}
pr = q[i].R;
if (pl < q[i].L)
{
for (int j = pl;j < q[i].L;j++)
update(j,-1);
}
else
{
for (int j = pl - 1;j >= q[i].L;j--)
update(j, 1);
}
pl = q[i].L;

aa = ans - (q[i].R - q[i].L + 1);
bb = (long long)(q[i].R - q[i].L + 1)*(q[i].R - q[i].L);

long long tmp = gcd(aa, bb);
aa /= tmp;
bb /= tmp;
q[i].ans1 = aa;
q[i].ans2 = bb;
}

sort(q + 1, q + 1 + m, cmp2);

for (int i = 1;i <= m;i++)
printf("%lld/%lld\n", q[i].ans1, q[i].ans2);
}
return 0;
}

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客