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

#include <cstdio>
#include <cmath>
#include <map>
#include <algorithm>
using namespace std;
#define MAXN 50003
#define MAXM 50003
int sqrtn;
struct qtype
{
int l, r, nu;
bool operator< (const qtype &x)const
{
int k1 = l / sqrtn, k2 = x.l / sqrtn;
return k1 < k2 || (k1 == k2 && r < x.r);
}
} q[MAXM];
int n, m, a[MAXN];
int ct[MAXN] = {0};
map<int, int> hash;
int cth = 0;
long long gcd(long long a, long long b)
{
while (b)
{
long long c = a % b;
a = b;
b = c;
}
return a;
}
long long ans1[MAXM], ans2[MAXM];
int main()
{
scanf("%d%d", &n, &m);
sqrtn = sqrt(n);
for (int i = 0; i < n; ++i)
scanf("%d", &a[i]);
for (int i = 0; i < n; ++i)
if (hash.find(a[i]) == hash.end())
a[i] = hash[a[i]] = cth++;
else
a[i] = hash[a[i]];
for (int i = 0; i < m; ++i)
{
scanf("%d%d", &q[i].l, &q[i].r);
q[i].nu = i;
--q[i].l;
}
sort(q, q + m);
int l = 0, r = 1;
ct[a[0]]++;
long long sum = 0;
for (int i = 0; i < m; ++i)
{
while (l < q[i].l)
{
long long t = ct[a[l]];
if (t > 1)
sum -= t * (t - 1) / 2;
if (t > 2)
sum += (t - 1) * (t - 2) / 2;
--ct[a[l++]];
}
while (l > q[i].l)
{
long long t = ct[a[l - 1]];
if (t > 1)
sum -= t * (t - 1) / 2;
if (t > 0)
sum += t * (t + 1) / 2;
++ct[a[--l]];
}
while (r < q[i].r)
{
long long t = ct[a[r]];
if (t > 1)
sum -= t * (t - 1) / 2;
if (t > 0)
sum += t * (t + 1) / 2;
++ct[a[r++]];
}
while (r > q[i].r)
{
long long t = ct[a[r - 1]];
if (t > 1)
sum -= t * (t - 1) / 2;
if (t > 2)
sum += (t - 1) * (t - 2) / 2;
--ct[a[--r]];
}
long long tmp = (long long)(r - l) * (r - l - 1) / 2;
long long c = gcd(sum, tmp);
ans1[q[i].nu] = sum / c;
ans2[q[i].nu] = tmp / c;
}
for (int i = 0; i < m; ++i)
#ifdef WINNT
printf("%I64d/%I64d\n", ans1[i], ans2[i]);
#else
printf("%lld/%lld\n", ans1[i], ans2[i]);
#endif
return 0;
}