离线的经典算法
先分块 然后按左端点所在的块先后顺序排序 再按右端点排序
L和R一直移动就好 不知道为什么感觉莫队就是优化+暴力
复杂度O(n^2)降到O(n^1.5)
分了个块也就排序用用o(╯□╰)o 之后就用不着了 很神奇的算法 表示已经被折服了
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<queue>
#include<vector>
#define M 50005
#define ll long long
using namespace std;
struct node{
int l,r,id;
ll ans,sum;
}Q[M];
ll ans;
int n,m,block[M],A[M];
ll cnt[M];
bool cmp(node a,node b){
if(block[a.l]!=block[b.l])return block[a.l]<block[b.l];
return a.r<b.r;
}
bool cmp1(node a,node b){
return a.id<b.id;
}
void Rd(int &res){
char c;res=0;
while(c=getchar(),!isdigit(c));
do res=(res<<1)+(res<<3)+(c^48);
while(c=getchar(),isdigit(c));
}
ll gcd(ll n,ll m){
if(m==0)return n;
else return gcd(m,n%m);
}
void init(){
Rd(n);Rd(m);
int limit=sqrt(n);
for(int i=1;i<=n;i++){
Rd(A[i]);
block[i]=(i-1)/limit+1;
cnt[A[i]]++;
ans+=cnt[A[i]]-1;
}
for(int i=1;i<=m;i++){
Rd(Q[i].l);Rd(Q[i].r);
Q[i].id=i;
Q[i].sum=1LL*(Q[i].r-Q[i].l+1)*(Q[i].r-Q[i].l)/2;
}
sort(Q+1,Q+m+1,cmp);
}
void update(ll x,ll y){
ans-=1ll*cnt[A[x]]*(cnt[A[x]]-1)/2;
cnt[A[x]]+=y;
ans+=1ll*cnt[A[x]]*(cnt[A[x]]-1)/2;
}
void solve(){
ll l=1,r=n;
for(int i=1;i<=m;i++){
while(l<Q[i].l){
update(l,-1);
l++;
}
while(l>Q[i].l){
update(l-1,1);
l--;
}
while(r<Q[i].r){
update(r+1,1);
r++;
}
while(r>Q[i].r){
update(r,-1);
r--;
}
Q[i].ans=ans;
}
sort(Q+1,Q+m+1,cmp1);
for(int i=1;i<=m;i++){
ll GCD=gcd(Q[i].sum,Q[i].ans);
printf("%lld/%lld\n",Q[i].ans/GCD,Q[i].sum/GCD);
//不知道为什么不能用cout RE无数次 一口老血喷了出
}
}
int main(){
init();
solve();
return 0;
}