分治一类的算法大多只能在离线时使用。莫队算法就是只能在离线下用。
先看一道模板题:小Z的袜子
Description
作为一个生活散漫的人,小Z每天早上都要耗费很久从一堆五颜六色的袜子中找出一双来穿。终于有一天,小Z再也无法忍受这恼人的找袜子过程,于是他决定听天由命……
具体来说,小Z把这N只袜子从1到N编号,然后从编号L到R(L 尽管小Z并不在意两只袜子是不是完整的一双,甚至不在意两只袜子是否一左一右,他却很在意袜子的颜色,毕竟穿两只不同色的袜子会很尴尬。
你的任务便是告诉小Z,他有多大的概率抽到两只颜色相同的袜子。当然,小Z希望这个概率尽量高,所以他可能会询问多个(L,R)以方便自己选择。
Input
输入文件第一行包含两个正整数N和M。N为袜子的数量,M为小Z所提的询问的数量。接下来一行包含N个正整数Ci,其中Ci表示第i只袜子的颜色,相同的颜色用相同的数字表示。再接下来M行,每行两个正整数L,R表示一个询问。
Output
包含M行,对于每个询问在一行中输出分数A/B表示从该询问的区间[L,R]中随机抽出两只袜子颜色相同的概率。若该概率为0则输出0/1,否则输出的A/B必须为最简分数。(详见样例)
莫队算法针对这个排序问题。
就是把每个询问 [l,r] 看做二维平面上的点(l,r),然后转移的复杂度就是曼哈顿距离,如何让曼哈顿距离和比较短?分块。
分块后按照S形排序,然后就没有然后了。
//Serene
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
using namespace std;
const int maxn=5e4+10;
long long n,m,size,ans1[maxn],ans2[maxn],c[maxn];
long long tot[maxn],ans,l,r;
long long aa;char cc;
long long read() {
aa=0;cc=getchar();
while(cc<'0'||cc>'9') cc=getchar();
while(cc>='0'&&cc<='9') aa=aa*10+cc-'0',cc=getchar();
return aa;
}
struct Node{
long long l,r,pos;
}node[maxn];
bool cmp(const Node& a,const Node& b) {
if(a.l/size!=b.l/size) return a.l/size<b.l/size;
if((a.l/size)&1) return a.r/size<b.r/size;
return a.r/size>b.r/size;
}
long long gcd(long long x,long long y) {
return y==0? x:gcd(y,x%y);
}
int main() {
n=read();m=read();
for(int i=1;i<=n;++i) c[i]=read();
for(int i=1;i<=m;++i) {
node[i].pos=i;
node[i].l=read();node[i].r=read();
ans2[i]=(node[i].r-node[i].l+1)*(node[i].r-node[i].l)/2;
}
size=sqrt(n);
sort(node+1,node+m+1,cmp);
l=node[1].l;r=node[1].r;
for(int i=l;i<=r;++i) {
ans+=tot[c[i]];
tot[c[i]]++;
}
ans1[node[1].pos]=ans;
for(int i=2;i<=n;++i) {
while(l>node[i].l) {
l--;
ans+=tot[c[l]];
tot[c[l]]++;
}
while(r<node[i].r) {
r++;
ans+=tot[c[r]];
tot[c[r]]++;
}
while(l<node[i].l) {
tot[c[l]]--;
ans-=tot[c[l]];
l++;
}
while(r>node[i].r) {
tot[c[r]]--;
ans-=tot[c[r]];
r--;
}
ans1[node[i].pos]=ans;
}
int x;
for(int i=1;i<=m;++i) {
if(ans1[i]==0||ans2[i]==0) {
printf("0/1\n");continue;
}
x=gcd(ans1[i],ans2[i]);
printf("%lld/%lld\n",ans1[i]/x,ans2[i]/x);
}
return 0;
}