题目描述
有一个长度为n的数组{a1,a2,…,an}。m次询问,每次询问一个区间内最小没有出现过的自然数。
思路
莫队水过去了 233
#include <bits/stdc++.h>
using namespace std;
const int maxn = 200000 + 10;
int n,m,now,block,cnt[maxn],a[maxn],ans[maxn];
struct Query {
int l,r,num;
inline bool operator < (Query cmp) const {
if (l/block != cmp.l/block) return l/block < cmp.l/block;
return r < cmp.r;
}
}q[maxn];
inline void add(int x) {
if (x > n+1) return;
cnt[x]++;
if (now == x && cnt[x] > 0)
for (int i = x;i <= n+1;i++)
if (!cnt[i]) {
now = i;
break;
}
}
inline void del(int x) {
if (x > n+1) return;
cnt[x]--;
if (!cnt[x]) now = min(now,x);
}
int main() {
scanf("%d%d",&n,&m);
block = sqrt(n);
a[0] = n+2;
for (int i = 1;i <= n;i++) scanf("%d",&a[i]);
for (int i = 1;i <= m;i++) {
scanf("%d%d",&q[i].l,&q[i].r);
q[i].num = i;
}
sort(q+1,q+m+1);
int l = 0,r = 0;
for (int i = 1;i <= m;i++) {
while (l < q[i].l) del(a[l++]);
while (l > q[i].l) add(a[--l]);
while (r < q[i].r) add(a[++r]);
while (r > q[i].r) del(a[r--]);
ans[q[i].num] = now;
}
for (int i = 1;i <= m;i++) printf("%d
",ans[i]);
return 0;
}