Description
The Little Elephant loves playing with arrays. He has array a, consisting of n positive integers, indexed from 1 to n. Let’s denote the number with index i as ai.
Additionally the Little Elephant has m queries to the array, each query is characterised by a pair of integers lj and rj (1 ≤ lj ≤ rj ≤ n). For each query lj, rj the Little Elephant has to count, how many numbers x exist, such that number x occurs exactly x times among numbers alj, alj + 1, …, arj.
Help the Little Elephant to count the answers to all queries.
Input
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the size of array a and the number of queries to it. The next line contains n space-separated positive integers a1, a2, …, an (1 ≤ ai ≤ 109). Next m lines contain descriptions of queries, one per line. The j-th of these lines contains the description of the j-th query as two space-separated integers lj and rj (1 ≤ lj ≤ rj ≤ n).
Output
In m lines print m integers — the answers to the queries. The j-th line should contain the answer to the j-th query.
Examples
Input
7 2
3 1 2 2 3 3 7
1 7
3 4
Output
3
1
题目大意
给定一个长度为n的数组,进行m次询问。每一次询问给出两个数l和r,表示在数组区间【l,r】内查询有多少数x使得x本身等于区间内x的个数。离线查询,一次性输出查询结果。
解题思路
很明显这道题可以用莫队算法来解决。定义数组num[]用来保存在给定区间内各个数出现的个数。要注意的是,数组中数的大小是10^9,很明显我们无法定义这么大的数组,因此要进行离散化处理。先将输入的数组排序后记录在一个新的数组中,再用另外一个数组记录已经排好序的数组中每个数在该数组中出现的最小位置(用lower-bound来求),这样就将10^9的数映射到10^5大小的数组中。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 100010, MOD = 1000000007;
struct node
{
int l, r, id;
} a[N];
int sum[N], b[N], c[N], Ans[N], num[N];
int n, m, ans, sz;
bool cmp(node a,node b)
{
return a.l/sz != b.l/sz ? a.l/sz < b.l/sz : a.r < b.r;
}
void add(int i)
{
if(num[c[i]] == sum[i] - 1) ans++;
else if(num[c[i]] == sum[i]) ans--;
num[c[i]]++;
}
void sub(int i)
{
if(num[c[i]] == sum[i]) ans--;
else if(num[c[i]] == sum[i] + 1) ans++;
num[c[i]]--;
}
void solve()
{
sz = (int)sqrt(1.0*n);
memset(num, 0, sizeof num);
sort(a+1, a+1+m, cmp);
int l = 1, r = 0;
ans = 0;
for(int i = 1; i <= m; i++)
{
while(r < a[i].r) add(++r);
while(r > a[i].r) sub(r--);
while(l < a[i].l) sub(l++);
while(l > a[i].l) add(--l);
Ans[a[i].id] = ans;
}
for(int i = 1; i <= m; i++) printf("%d\n", Ans[i]);
}
int main()
{
cin>>n>>m;
for(int i = 1; i <= n; i++)
{
scanf("%d", &sum[i]);
c[i] = b[i] = sum[i];
}
sort(b+1, b+1+n);
for(int i = 1; i <= n; i++)
{
c[i] = lower_bound(b+1, b+1+n, c[i]) - b; //离散化处理
}
for(int i = 1; i <= m; i++)
{
scanf("%d%d", &a[i].l, &a[i].r);
a[i].id = i;
}
solve();
return 0;
}