bzoj3585 mex

bzoj3585 mex

静态区间 \(\operatorname{mex}\)

\(n, m\leq2\times10^5,\ 0\leq a_i\leq10^9\)

莫队+值域分块


莫队,有 \(O(n\sqrt n)\) 次修改, \(O(m)\) 次查询,显然不能用 \(O(\log n)\) 修改, \(O(\log n)\) 查询的线段树。 用 \(O(1)\) 修改, \(O(\sqrt n)\) 查询的值域分块就可以辣。同时 \(a_i>n\) 的数可以忽略。

也可以用线段树维护 \(lst\) 值,主席树/离线搞一搞,咕咕咕

时间复杂度 \(O((n+m)\sqrt n)\)

代码

#include <bits/stdc++.h>
using namespace std;

const int maxn = 2e5 + 10;
int n, m, bsz, cnt[1010], a[maxn], c[maxn], bl[maxn], ans[maxn];
struct Query {
  int l, r, tid;
  bool operator < (const Query& o) const {
    return bl[l] == bl[o.l] ? r > o.r : l < o.l;
  }
} Q[maxn];

void add(int x) {
  if (x <= n) cnt[bl[x]] += !c[x]++;
}

void del(int x) {
  if (x <= n) cnt[bl[x]] -= !--c[x];
}

int main() {
  scanf("%d %d", &n, &m);
  bsz = sqrt(n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", a + i);
    bl[i] = (i - 1) / bsz + 1;
  }
  for (int i = 1; i <= m; i++) {
    Q[i].tid = i;
    scanf("%d %d", &Q[i].l, &Q[i].r);
  }
  sort(Q + 1, Q + m + 1);
  int l = 1, r = 0;
  for (int i = 1; i <= m; i++) {
    while (l > Q[i].l) add(a[--l]);
    while (r < Q[i].r) add(a[++r]);
    while (l < Q[i].l) del(a[l++]);
    while (r > Q[i].r) del(a[r--]);
    if (!c[0]) continue;
    int pos = 1;
    while (cnt[pos] == bsz) pos++;
    pos = (pos - 1) * bsz + 1;
    while (c[pos]) pos++;
    ans[Q[i].tid] = pos;
  }
  for (int i = 1; i <= m; i++) {
    printf("%d\n", ans[i]);
  }
  return 0;
}
posted @ 2019-03-03 14:22  cnJuanzhang  阅读(149)  评论(0编辑  收藏  举报