Description
给你一个长度为 (n) 的序列 (C) , (m) 次询问,每次询问序列的子区间 ([l,r]) 中随机选出两个数,数值相同的概率。
(1leq n,m,C_ileq 50000)
Solution
右端点向右移时,假设这时候在该序列中是将要移动到的右端点的位置代表的颜色个数为 (cnt) 个,那么移动之后就会新产生 (cnt) 对颜色相同的数对。开一个数组记录下区间内相同颜色的个数即可。
Code
//It is made by Awson on 2018.2.22
#include <bits/stdc++.h>
#define LL long long
#define dob complex<double>
#define Abs(a) ((a) < 0 ? (-(a)) : (a))
#define Max(a, b) ((a) > (b) ? (a) : (b))
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define Swap(a, b) ((a) ^= (b), (b) ^= (a), (a) ^= (b))
#define writeln(x) (write(x), putchar('
'))
#define lowbit(x) ((x)&(-(x)))
using namespace std;
const int N = 50000;
void read(int &x) {
char ch; bool flag = 0;
for (ch = getchar(); !isdigit(ch) && ((flag |= (ch == '-')) || 1); ch = getchar());
for (x = 0; isdigit(ch); x = (x<<1)+(x<<3)+ch-48, ch = getchar());
x *= 1-2*flag;
}
void print(LL x) {if (x > 9) print(x/10); putchar(x%10+48); }
void write(LL x) {if (x < 0) putchar('-'); print(Abs(x)); }
int n, m, lim, a[N+5], cnt[N+5];
struct tt {
int l, r, id;
bool operator < (const tt &b) const {return l/lim == b.l/lim ? r < b.r : l < b.l; }
}q[N+5];
LL ans[N+5], tol[N+5];
LL gcd(LL a, LL b) {return b ? gcd(b, a%b) : a; }
void work() {
read(n), read(m); lim = sqrt(n); for (int i = 1; i <= n; i++) read(a[i]);
for (int i = 1; i <= m; i++) read(q[i].l), read(q[i].r), q[i].id = i, tol[i] = 1ll*(q[i].r-q[i].l)*(q[i].r-q[i].l+1)/2;
sort(q+1, q+m+1);
int curl = 1, curr = 0; LL sum = 0;
for (int i = 1; i <= m; i++) {
int l = q[i].l, r = q[i].r;
while (curr < r) sum += cnt[a[++curr]]++;
while (curl > l) sum += cnt[a[--curl]]++;
while (curr > r) sum -= --cnt[a[curr--]];
while (curl < l) sum -= --cnt[a[curl++]];
ans[q[i].id] = sum;
}
for (int i = 1; i <= m; i++)
if (ans[i] == 0) puts("0/1");
else {int d = gcd(ans[i], tol[i]); write(ans[i]/d), putchar('/'), writeln(tol[i]/d); }
}
int main() {
work(); return 0;
}