题解:P7764 [COCI 2016/2017 #5] Poklon

· · 题解

题意

给定一个长度为 n 的序列 a。q 次询问 l,r,求出 a[l,r] 中恰好出现两次的数的个数。1\leq n,q\leq 5\times 10^5,0\leq a_i\leq 10^9。

题解

唐题。

先 \mathcal{O}(n\log{n}) 离散化,值域变成 [1,m]。预处理 pre_i 表示 a_i 前面第一个与 a_i 相同的数。

把询问离线,按右端点排序,然后扫描线。我们当然希望通过巧妙地打标记,使得查询标记数组 b 的区间和 [l,r] 恰好就是我们所需的答案。考虑在数 a_i=v 第二次出现时计入贡献,那么我们打的标记应该形如

\begin{matrix} & pre_{pre_i} & pre_i & i \\ & -1 & +1 & 0 \end{matrix}

因此每次遇到一个新的 a_i 时,我们给 b_{pre_i} 单点 +1,给 b_{pre_{pre_i}} 单点 -2,给 b_{pre_{pre_{pre_i}}} 单点 +1 即可。

用 BIT 维护 b 的单点加、区间和。时间复杂度 \mathcal{O}(n\log{n})。

代码

#include <iostream>
#include <algorithm>

using namespace std;

#define lowbit(x) ((x) & -(x))
#define chk_min(x, v) (x) = min((x), (v))
#define chk_max(x, v) (x) = max((x), (v))
typedef long long ll;
typedef pair<int, int> pii;
const int N = 5e5 + 5;

int n, q, ans[N], a[N], pre[N], pos[N];
int sz, d[N];
struct Query { int id, l, r; } qr[N];
bool cmp(Query a, Query b) { return a.r < b.r; }

struct BIT {
    int c[N];
    inline int query(int x) {
        int res = 0;
        for (; x; x -= lowbit(x)) res += c[x];
        return res;
    }
    inline int query(int l, int r) { return query(r) - query(l - 1); }
    inline void add(int x, int v) { for (; x <= n; x += lowbit(x)) c[x] += v; }
} ft;

int main() {
    ios::sync_with_stdio(0), cin.tie(0);
    cin >> n >> q;
    for (int i = 1; i <= n; ++i) cin >> a[i], d[i] = a[i];
    sort(d + 1, d + n + 1), sz = unique(d + 1, d + n + 1) - (d + 1);
    for (int i = 1; i <= n; ++i) {
        a[i] = lower_bound(d + 1, d + sz + 1, a[i]) - d;
        pre[i] = pos[a[i]], pos[a[i]] = i;
    }
    for (int i = 1, l, r; i <= q; ++i) cin >> l >> r, qr[i] = {i, l, r};
    sort(qr + 1, qr + q + 1, cmp);
    for (int i = 1, j = 1; i <= n; ++i) {
        if (pre[i]) ft.add(pre[i], 1);
        if (pre[pre[i]]) ft.add(pre[pre[i]], -2);
        if (pre[pre[pre[i]]]) ft.add(pre[pre[pre[i]]], 1);
        while (j <= q && qr[j].r == i) ans[qr[j].id] = ft.query(qr[j].l, qr[j].r), ++j;
    }
    for (int i = 1; i <= q; ++i) cout << ans[i] << '\n';
    return 0;
}