Codeforces Round #136 (Div. 1) B. Little Elephant and Array 莫队裸题

#include<bits/stdc++.h>
#define  ll unsigned long long
using namespace std;

/**********************************************Head-----Template****************************************/
bool Finish_read;
template<class T>inline void read(T &x){Finish_read=0;x=0;int f=1;char ch=getchar();while(!isdigit(ch)){if(ch=='-')f=-1;if(ch==EOF)return;ch=getchar();}while(isdigit(ch))x=x*10+ch-'0',ch=getchar();x*=f;Finish_read=1;}
template<class T>inline void print(T x){if(x/10!=0)print(x/10);putchar(x%10+'0');}
template<class T>inline void writeln(T x){if(x<0)putchar('-');x=abs(x);print(x);putchar('\n');}
template<class T>inline void write(T x){if(x<0)putchar('-');x=abs(x);print(x);}
ll gcd(ll a,ll b){return b==0?a:gcd(b,a%b);}
ll lcm(ll a,ll b){ll gg=gcd(a,b);a/=gg;if(a<=LLONG_MAX/b) return a*b;return LLONG_MAX;}
/********************************Head----Temlate**********************************************/

const int maxn=2e6+7;
int s[maxn],pos[maxn];
int n,m;

int val[maxn];
int cnt[maxn];

struct node{
    int l,r,id;
    bool operator <(const node &a)const{
        return pos[l]<pos[a.l]||(pos[l]==pos[a.l]&&r<a.r);
    }
}a[maxn];

int tmp[maxn];//原数对应位置的值对应在原序列的排位

int tmp_num[maxn];//原序列对应排位位置的值;

int aa[maxn];

int main (){
    int n,t;read(n);read(t);m=sqrt(n);
    for(int i=1;i<=n;i++){
        read(s[i]);tmp[i]=s[i];
        pos[i]=(i-1)/m+1;
    }
    sort(s+1,s+1+n);
    int ret=unique(s+1,s+1+n)-(s+1);
    for(int i=1;i<=n;i++) tmp[i]=lower_bound(s+1,s+1+ret,tmp[i])-s,tmp_num[i]=s[i];
    /**
    原序列: tmp[i]  3 1 2 2 3 3 7
    更新后   tmp[i]  3 1 2 2 3 3 4
     tmp_num[i] = s[i]    1 2 3 7 3 3 7

     */
    for(int i=1;i<=t;i++){
        read(a[i].l),read(a[i].r);
        a[i].id=i;
    }

    sort(a+1,a+1+t);
    int l=1,r=0;
    int ans=0;
    for(int i=1;i<=t;i++) {

        while(l>a[i].l){
            if(cnt[tmp[l-1]]==tmp_num[tmp[l-1]]) ans--;
            l--;
            cnt[tmp[l]]++;
            if(cnt[tmp[l]]==tmp_num[tmp[l]]) ans++;
        }


        while(r<a[i].r){
            if(cnt[tmp[r+1]]==tmp_num[tmp[r+1]]) ans--;
            r++;
            cnt[tmp[r]]++;
            if(cnt[tmp[r]]==tmp_num[tmp[r]]) ans++;
        }


        while(l<a[i].l){
             if(cnt[tmp[l]]==tmp_num[tmp[l]]) ans--;
             cnt[tmp[l]]--;
             if(cnt[tmp[l]]==tmp_num[tmp[l]]) ans++;
             l++;
        }


        while(r>a[i].r){
            if(cnt[tmp[r]]==tmp_num[tmp[r]]) ans--;
            cnt[tmp[r]]--;
            if(cnt[tmp[r]]==tmp_num[tmp[r]]) ans++;
            r--;
        }


        val[a[i].id]=ans;
    }
    for(int i=1;i<=t;i++) writeln(val[i]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hypHuangYanPing/article/details/81781934