题目链接
初学莫队,所以用莫队来解题,但不是计算区间内有几个不同的数,所以稍微修改add和del函数的内部即可
需要注意的是,数组的长度最大为1e5,那么大于1e5的数是不可能满足条件的,所以在函数内部直接return掉(否则会RE,但计数的cnt数组是开不了1e9的)
AC代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e6 + 5;
LL aa[N], cnt[N], belong[N],ans[N],now,n,m;
struct node
{
LL l, r, id;
}q[N];
void add(LL i)
{
if (aa[i] > N) return; //防止越界,直接return
if (cnt[aa[i]] == aa[i]) now--;//如果原来相等,那么加入新的数后肯定不相等,答案的数量就-1
cnt[aa[i]]++; //aa[i]在区间内的数量+1
if (cnt[aa[i]]==aa[i]) now++; //如果加入后符合条件,答案+1
}
void del(LL i) //同上
{
if (aa[i] > N) return;
if (cnt[aa[i]] == aa[i]) now--;
cnt[aa[i]]--;
if (cnt[aa[i]]==aa[i]) now++;
}
int cmp(const struct node& a, const struct node& b)
{
return (belong[a.l] ^ belong[b.l]) ? belong[a.l] < belong[b.l] : ((belong[a.l] & 1) ? a.r < b.r : a.r > b.r);
}
inline LL read() {
LL x = 0, f = 1; char ch = getchar();
while (ch<'0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }
while ('0' <= ch && ch <= '9') { x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar(); }
return x * f;
}
inline void printi(LL x) {
if (x / 10) printi(x / 10);
putchar(x % 10 + '0');
}
int main()
{
cin >> n;
LL sz = sqrt(n);
m = read();
for (LL i = 1; i <= n; i++)
{
aa[i] = read();
belong[i] = (i - 1) / sz + 1;
}
for (LL i = 1; i <= m; i++)
{
q[i].l = read();
q[i].r = read();
q[i].id = i;
}
sort(q + 1, q + 1 + m, cmp);
LL l = 1, r = 0;
for (LL i = 1; i <= m; i++)
{
int ql = q[i].l,qr=q[i].r;
while (l < ql) del(l++);
while (l > ql) add(--l);
while (r < qr) add(++r);
while (r > qr) del(r--);
ans[q[i].id] = now;
}
for (LL i = 1; i <= m; i++)
{
printi(ans[i]);
putchar('\n');
}
}