跳到正文

个人记录

有关区间内出现k次数的数量问题

xinhuo2005约 5 分钟
原文
文章信息与版本

文章信息

发布
2024年11月9日
收录
2025年12月12日
更新
2026年9月26日
篇幅
约 5 分钟

版本

  1. v1当前

对于此类问题,我们发现,如果指定一个区间 (l, r)(l, ~r) ,那么对于每一个数 xx ,只有在这个区间内,距离 rr 有第 kk 远的 xx 才行,所以我们只需要在第 kk 个数 xx 上打上标记 +1+1 即可,同时,防止多次加,我们还需要在第 k+1k + 1 远处的 xx 打上标记 −1-1 ,来撤销之前的影响。

洛谷 P1972P1972

查询一些区间内,出现的不同的数的个数,也就是 k=1k = 1 的情况,很简单,只需要对于每一个数 xx ,我们在距离 rr 最近的位置打上 +1+1 , 在次远处打上 −1-1 即可,但是每次维护都是 O(len)O(len) 的,所以我们可以离线记录查询,按右端点升序排序,就可以 O(n)O(n) 的完成查询的过程了

C++
struct Q {
    int l, r, id;
    bool operator< (const Q& a) const {
        return r < a.r;
    }
};

int main() {
    int n = read();

    std::vector<int> a(n + 1);
    int mx = 0;
    for (int i = 1; i <= n; i++) {
        a[i] = read();
        if (mx < a[i]) mx = a[i];
    }
    Fenwick T;
    T.init(n);

    int m = read();
    std::vector<Q> q(m);
    std::vector<int> ans(m);
    std::vector<int> pos(mx + 1);
    for (int i = 0; i < m; i++) {
        q[i].l = read();
        q[i].r = read();
        q[i].id = i;
    }

    std::sort(q.begin(), q.end());
    int now = 1;
    for (int i = 0; i < m; i++) {
        for (int j = now; j <= q[i].r; j++) {
            if (pos[a[j]])  T.add(pos[a[j]], -1);
            pos[a[j]] = j;
            T.add(j, 1);
        }
        ans[q[i].id] = T.rangeSum(q[i].l, q[i].r);
        now = q[i].r + 1;
    }
    for (int i = 0; i < m; i++) {
        printf("%d\n", ans[i]);
    }
    return 0;
}

洛谷 P4113P4113

问区间内出现两次及以上的花有多少个,一样的维护就行

C++
struct Q{
    int l, r, id;

    bool operator< (const Q& a) const {
        return r < a.r;
    }
};

int main() {
    int n, c, m;
    std::cin >> n >> c >> m;
    std::vector<int> a(n + 1);
    for (int i = 1; i <= n; i++) {
        a[i] = read();
    }
    std::vector<Q> qry(m);
    for (int i = 0; i < m; i++) {
        qry[i].l = read();
        qry[i].r = read();
        qry[i].id = i;
    }

    std::sort(qry.begin(), qry.end());
    Fenwick T;
    T.init(n);
    std::vector<int> pos(c + 1), pos1(c + 1);
    std::vector<int> ans(m);
    int now = 1;
    for (int i = 0; i < m; i++) {
        for (int j = now; j <= qry[i].r; j++) {
            if (pos[a[j]]) {
                T.add(pos[a[j]], 1);
                if (pos1[a[j]]) T.add(pos1[a[j]], -1);
                pos1[a[j]] = pos[a[j]];
            }
            pos[a[j]] = j;
        }
        now = qry[i].r + 1;
        ans[qry[i].id] = T.rangeSum(qry[i].l, qry[i].r);
    }

    for (int i = 0; i < m; i++) {
        printf("%d\n", ans[i]);
    }
    return 0;
}
原文