传送门
题意
小象喜欢和数组玩。现在有一个数组。 a a a,含有 n n n正整数,记第 i i i个数为 a i a_i ai
现在有 m m m每个问题包括两个正整数 l j l_j lj和 r j ( 1 < = l j < = r j < = n ) r_j(1<=l_j<=r_j<=n) rj(1<=lj<=rj<=n),小象想知道在 l l l到 r r r之中有多少个数 x x x,其出现次数也为 x x x
分析
比较容易想到的是莫队的思路,类似于HH的项链那道题,暴力维护即可 还有一种二分的做法也能过,但是测了一下跑的有点慢,大概需要 2000 m s 2000ms 2000ms多
代码
//莫队
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10;
const ll mod = 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a) {
char c = getchar(); T x = 0, f = 1; while (!isdigit(c)) {
if (c == '-')f = -1; c = getchar();}
while (isdigit(c)) {
x = (x << 1) + (x << 3) + c - '0'; c = getchar();} a = f * x;
}
int gcd(int a, int b) {
return (b > 0) ? gcd(b, a % b) : a;}
struct Node{
int id,l,r;
}q[N];
int n,m,len;
int w[N],ans[N];
int cnt[N];
int get(int x){
return x / len;
}
bool cmp(const Node &A,const Node &B){
int i = get(A.l),j = get(B.l);
if(i != j) return i < j;
return A.r < B.r;
}
void add(int x,int &res){
if(x > n) return;
if(cnt[x] == x) res--;
cnt[x]++;
if(cnt[x] == x) res++;
}
void del(int x,int &res){
if(x > n) return;
if(cnt[x] == x) res--;
cnt[x]--;
if(cnt[x] == x) res++;
}
int main() {
read(n),read(m);
for(int i = 1;i <= n;i++) read(w[i]);
len = sqrt((double) n);
for(int i = 0;i < m;i++){
int l,r;
read(l),read(r);
q[i] = {
i,l,r};
}
sort(q,q + m,cmp);
for(int k = 0,i = 0,j = 1,res = 0;k < m;k++){
int id = q[k].id,l = q[k].l,r = q[k].r;
while(i < r) add(w[++i],res);
while(i > r) del(w[i--],res);
while(j < l) del(w[j++],res);
while(j > l) add(w[--j],res);
ans[id] = res;
}
for(int i = 0;i < m;i++) {
di(ans[i]);}
return 0;
}