题解:
题目要求输出分数
那么分母就是n*n
分子就是总数=相同颜色^2
然后用莫队来做
代码:
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=50005; int n,m,Be[N],ans,sum[N],col[N]; struct Mo { int l,r,id; ll A,B; }q[N]; ll S(ll x) { return x*x; } ll gcd(ll x,ll y) { if (!y)return x; return gcd(y,x%y); } int cmp(Mo a,Mo b) { if (Be[a.l]==Be[b.l])return a.r<b.r; return a.l<b.l; } int cmp1(Mo a,Mo b) { return a.id<b.id; } void revise(int x,int add) { ans-=S(sum[col[x]]); sum[col[x]]+=add; ans+=S(sum[col[x]]); } int main() { scanf("%d%d",&n,&m); for (int i=1;i<=n;i++) { scanf("%d",&col[i]); Be[i]=i/(int)sqrt(n)+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+m+1,cmp); int l=1,r=0; for (int i=1;i<=m;i++) { while (l<q[i].l)revise(l,-1),l++; while (l>q[i].l)revise(l-1,1),l--; while (r<q[i].r)revise(r+1,1),r++; while (r>q[i].r)revise(r,-1),r--; if (q[i].l==q[i].r) { q[i].A=0; q[i].B=1; continue; } q[i].A=ans-(q[i].r-q[i].l+1); q[i].B=1LL*(q[i].r-q[i].l+1)*(q[i].r-q[i].l); ll gc=gcd(q[i].A,q[i].B); q[i].A/=gc; q[i].B/=gc; } sort(q+1,q+m+1,cmp1); for (int i=1;i<=m;i++)printf("%lld/%lld\n",q[i].A,q[i].B); }