CodeForces - 220B Little Elephant and Array (莫队+离散化)

本文解决了一个编程挑战,小象与数组的问题,涉及数组操作和查询处理。通过离散化处理和Mo's算法,有效地解决了在给定区间内寻找出现次数等于其值的元素数量的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值