莫队算法可解决的类型题:
给定n个数,有q次询问,每次询问一个区间的某个属性(因题而异)。
关于莫队算法的详解见以下博客:
https://blog.csdn.net/ThinFatty/article/details/72581276
https://blog.csdn.net/hnshhslsh/article/details/50582926#对上述算法的复杂性证明-o-sqrt-n-n
其实莫队算法的核心就是,对给定数组进行分块处理,接着对所询问的区间进行排序,以此来改变询问的次序,从而减小时间复杂度。
注意:莫队算法由于需要对区间进行排序,所以它所解决的题必须是允许离线处理的才行。
在vjudge上找到了一道模板题:
Given a sequence of n numbers a1, a2, …, an and a number of
d-queries. A d-query is a pair (i, j) (1 ≤ i ≤ j ≤ n). For each
d-query (i, j), you have to return the number of distinct elements in
the subsequence ai, ai+1, …, aj.Input
Line 1: n (1 ≤ n ≤ 30000).
Line 2: n numbers a1, a2, …, an (1≤ ai ≤ 106).
Line 3: q (1 ≤ q ≤ 200000), the number of d-queries. In
the next q lines, each line contains 2 numbers i, j representing a
d-query (1 ≤ i ≤ j ≤ n).
Output
For each d-query (i, j), print thenumber of distinct elements in the subsequence ai, ai+1, …, aj in a single line. Example Input 5 1 1 2 1 3 3 1 5 2 4 3 5Input
5
1 1 2 1 3
3
1 5
2 4
3 5
Output
3
2
3
代码如下:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
int ans[maxn*2],block,temp;
int check[maxn*10],a[30005];
struct query
{
int l;
int r;
int num;
}qy[2*maxn];
bool cmp(query x,query y)
{
if(x.l/block!=y.l/block)
return x.l<y.l;
if(x.l/block&1) //使用波形排序,可进一步的优化
return x.r<y.r;
return x.r>y.r;
}
void add(int x)
{
if(!check[x])
temp++;
check[x]++;
}
void remove(int x)
{
if(check[x]==1)
temp--;
check[x]--;
}
int main()
{
int n,q;
memset(check,0,sizeof(check));
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
scanf("%d",&q);
for(int i=1;i<=q;i++)
{
scanf("%d%d",&qy[i].l,&qy[i].r);
qy[i].num=i;
}
block=sqrt(n);temp=0;
sort(qy+1,qy+1+q,cmp);
int left=1,right=1;
add(a[1]);
for(int i=1;i<=q;i++)
{
while(left<qy[i].l){ remove(a[left++]);
}
while(left>qy[i].l){ add(a[--left]);
}
while(right<qy[i].r){ add(a[++right]);
}
while(right>qy[i].r){ remove(a[right--]);
}
ans[qy[i].num]=temp;
}
for(int i=1;i<=q;i++)
printf("%d\n",ans[i]);
return 0;
}