莫队算法经典题
莫队算法学了三天多,才总算看懂,网上的资料真是太少了,论文也找不到,网上大佬们都说1h就看懂了,超简单的,简直泪奔~~前车之鉴,附上辛辛苦苦找到的优秀博客!!!
http://foreseeable97.logdown.com/posts/158522-233333
https://blog.youkuaiyun.com/hnshhslsh/article/details/50582926#
https://zhuanlan.zhihu.com/p/25017840
https://blog.youkuaiyun.com/xh413235699/article/details/77840659
看不懂,你过来打我!!!
附本题Code(一些小细节):
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int Max_n=1e5+10;
int n,m;
int s[Max_n],pos[Max_n];
ll ans,cnt[Max_n];
struct node{
int l,r,id;
ll a,b;
}no[Max_n];
bool cmp1(const node& n1,const node& n2){
if(pos[n1.l]==pos[n2.l])return n1.r<n2.r;
return n1.l<n2.l;
}
bool cmp2(const node& n1,const node& n2){
return n1.id<n2.id;
}
ll gcd(ll a,ll b){
if(b==0)return a;
return gcd(b,a%b);
}
void update(int x,int d){
ans-=cnt[s[x]]*cnt[s[x]];
cnt[s[x]]+=d;
ans+=cnt[s[x]]*cnt[s[x]];
}
int main()
{
scanf("%d%d",&n,&m);
int unit=sqrt(n); //分为√n块
for(int i=1;i<=n;i++){
scanf("%d",&s[i]);
pos[i]=i/unit;
}
for(int i=1;i<=m;i++){
scanf("%d%d",&no[i].l,&no[i].r);
no[i].id=i;
}
sort(no+1,no+m+1,cmp1);
memset(cnt,0,sizeof(cnt));
int l=1,r=0; //l=r+1(调试一下就晓得)
ans=0;
for(int i=1;i<=m;i++){
while(l<no[i].l)update(l++,-1);
while(l>no[i].l)update(--l,1);
while(r<no[i].r)update(++r,1);
while(r>no[i].r)update(r--,-1);
ll a=ans-(r-l+1); //此时l=no[i].l r=no[i].r
ll b=(ll)(r-l+1)*(r-l); //爆int
ll c=gcd(a,b);
no[i].a=a/c;no[i].b=b/c;
}
sort(no+1,no+m+1,cmp2);
for(int i=1;i<=m;i++)printf("%lld/%lld\n",no[i].a,no[i].b);
return 0;
}