原来这就是传说中的莫队算法。。感觉就是个暴力啊qwq。。。
莫队算法
离线处理区间无修改查询问题。
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#define N 50005
#define ll long long
using namespace std;
int n,m,pos[N],c[N];
ll s[N],ans;
struct node {int l,r,id; ll a,b;} a[N];
ll gcd(ll a,ll b)
{
return b==0?a:gcd(b,a%b);
}
ll sqr(ll x)
{
return x*x;
}
inline int read()
{
int a=0,f=1; char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1; c=getchar();}
while (c>='0'&&c<='9') {a=a*10+c-'0'; c=getchar();}
return a*f;
}
inline bool cmp(node a,node b)
{
return pos[a.l]==pos[b.l]?a.r<b.r:a.l<b.l;
}
inline bool cmp0(node a,node b)
{
return a.id<b.id;
}
inline void update(int p,int add)
{
ans-=sqr(s[c[p]]);
s[c[p]]+=add;
ans+=sqr(s[c[p]]);
}
int main()
{
n=read(); m=read();
for (int i=1;i<=n;i++) c[i]=read();
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++)
a[i].l=read(),a[i].r=read(),a[i].id=i;
sort(a+1,a+m+1,cmp);
int l=1,r=0;
for (int i=1;i<=m;i++)
{
for (;r<a[i].r;r++) update(r+1,1);
for (;r>a[i].r;r--) update(r,-1);
for (;l<a[i].l;l++) update(l,-1);
for (;l>a[i].l;l--) update(l-1,1);
if (a[i].l==a[i].r)
{
a[i].a=0; a[i].b=1;
continue;
}
a[i].a=ans-(a[i].r-a[i].l+1);
a[i].b=(ll)(a[i].r-a[i].l+1)*(a[i].r-a[i].l);
ll k=gcd(a[i].a,a[i].b);
a[i].a/=k; a[i].b/=k;
}
sort(a+1,a+m+1,cmp0);
for (int i=1;i<=m;i++)
printf("%lld/%lld\n",a[i].a,a[i].b);
return 0;
}