https://www.luogu.org/problemnew/show/P1494
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const int M=5e4+4; 5 struct node{ 6 int l,r,pos,id; 7 bool operator <(const node &x){ 8 if(x.pos==pos) 9 return r<x.r; 10 else 11 return pos<x.pos; 12 } 13 }b[M]; 14 ll a[M],ANSzi[M],ANSmu[M],cnt[M],flag[M]; 15 int main(){ 16 int n,m; 17 scanf("%d%d",&n,&m); 18 for(int i=1;i<=n;i++) 19 scanf("%lld",&a[i]); 20 int N=(int)sqrt(n); 21 for(int i=1;i<=m;i++){ 22 scanf("%d%d",&b[i].l,&b[i].r); 23 b[i].pos=(b[i].l-1)/N+1; 24 b[i].id=i; 25 } 26 sort(b+1,b+1+m); 27 int l=1,r=0; 28 ll ans=0; 29 for(int i=1;i<=m;i++){ 30 if(b[i].l==b[i].r){ 31 flag[b[i].id]=1; 32 continue; 33 } 34 // cout<<"*********"<<b[i].id<<"*********"<<endl; 35 while(l>b[i].l) 36 l--,ans+=cnt[a[l]],cnt[a[l]]++; 37 // cout<<ans<<endl; 38 while(r<b[i].r) 39 r++,ans+=cnt[a[r]],cnt[a[r]]++; 40 // cout<<ans<<endl; 41 while(l<b[i].l) 42 ans-=cnt[a[l]]==0?0:cnt[a[l]]-1,cnt[a[l]]--,l++; 43 // cout<<ans<<endl; 44 while(r>b[i].r) 45 ans-=cnt[a[r]]==0?0:cnt[a[r]]-1,cnt[a[r]]--,r--; 46 // cout<<ans<<endl; 47 ANSzi[b[i].id]=ans,ANSmu[b[i].id]=(b[i].r-b[i].l+1)*1ll*(b[i].r-b[i].l)*1ll/2; 48 // cout<<"l==="<<l<<"r==="<<r<<endl; 49 // cout<<ans<<endl; 50 } 51 for(int i=1;i<=m;i++){ 52 if(flag[i]==1||ANSzi[i]==0){ 53 printf("0/1 "); 54 continue; 55 } 56 int sign=__gcd(ANSzi[i],ANSmu[i]); 57 printf("%lld/%lld ",ANSzi[i]/sign,ANSmu[i]/sign); 58 59 } 60 return 0; 61 }