Little Elephant and Array
The Little Elephant loves playing with arrays. He has array a, consisting of npositive 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, rjthe Little Elephant has to count, how many numbers x exist, such that number xoccurs 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
题目链接:http://codeforces.com/problemset/problem/220/B
题目大意:一个长度为n的数列,m次查询,每次查询 求出区间 l 到 r 区间内有几个数 x 在区间内出现了x次
思路:因为ai最大到了10^9没办法标记,所以先对数组a进行离散化处理,然后就是莫队模板题
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
const int N=200010;
int a[N],ans,c[N],b[N],e[N],k;
struct node
{
int l,r,id,pos;
}q[N];
bool cmp(node a,node b)
{
if(a.pos==b.pos) return a.r<b.r;
return a.pos<b.pos;
}
void update(int x,int p)
{
if(x==0) return ;
int y=lower_bound(e+1,e+1+k,a[x])-e;
if(c[y]==a[x]) ans-=1;
c[y]+=p;
if(c[y]==a[x]) ans+=1;
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
int p=sqrt(n);
for(int i=1;i<=n;i++) scanf("%d",&a[i]),e[i]=a[i];
sort(e+1,e+1+n);
k=unique(e+1,e+n+1)-(e+1);
for(int i=0;i<m;i++)
{
scanf("%d%d",&q[i].l,&q[i].r);
q[i].id=i;
q[i].pos=q[i].l/p;
}
sort(q,q+m,cmp);
int l=0,r=0;
ans=0;
for(int i=0;i<m;i++)
{
while(l<q[i].l) update(l++,-1);
while(l>q[i].l) update(--l,1);
while(r>q[i].r) update(r--,-1);
while(r<q[i].r) update(++r,1);
b[q[i].id]=ans;
}
for(int i=0;i<m;i++)
printf("%d\n",b[i]);
return 0;
}