题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=2038
思路:直接莫队,模板题,注意longlong
代码:
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define fuck(x) cout<<"<"<<x<<">"<<endl
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
const int maxn = 5e4 + 5;
const int mod = 1e9 + 7;
int n, m;
int a[maxn],pos[maxn];
LL ansx[maxn],ansy[maxn];
LL sum;
LL num[maxn];
struct query {
int l, r, id;
} q[200005];
bool cmp(query a,query b){
return pos[a.l]==pos[b.l]?a.r<b.r:pos[a.l]<pos[b.l];
}
LL gcd(LL a,LL b){
return b?gcd(b,a%b):a;
}
void add(int pos) {
sum-=num[a[pos]]*num[a[pos]];
num[a[pos]]++;
sum+=num[a[pos]]*num[a[pos]];
}
void reduce(int pos) {
sum-=num[a[pos]]*num[a[pos]];
num[a[pos]]--;
sum+=num[a[pos]]*num[a[pos]];
}
int main() {
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
int block=int(sqrt(n));
for (int i=1;i<=n;i++) pos[i]=(i-1)/block+1;
for (int i=1;i<=m;i++){
scanf ("%d%d",&q[i].l,&q[i].r);
q[i].id=i;
}
sort(q+1,q+1+m,cmp);
int l=1,r=0;
sum=0;
for (int i=1;i<=m;i++){
int id=q[i].id;
while (r<q[i].r) add(++r);
while (r>q[i].r) reduce(r--);
while (l>q[i].l) add(--l);
while (l<q[i].l) reduce(l++);
ansx[id]=sum-(q[i].r-q[i].l+1);
ansy[id]=(LL)(q[i].r-q[i].l+1)*(q[i].r-q[i].l);
if (ansx[id]==0) {
ansy[id]=1;
continue;
}
LL tmp=gcd(ansx[id],ansy[id]);
ansx[id]=ansx[id]/tmp;
ansy[id]=ansy[id]/tmp;
}
for (int i=1;i<=m;i++){
printf ("%lld/%lld\n",ansx[i],ansy[i]);
}
return 0;
}