跳到正文

题解

题解:P14340 [JOISC 2019] 考试 / Examination

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

文章信息

发布
2025年10月31日
收录
2025年12月12日
更新
2026年10月26日
篇幅
约 5 分钟
题目
P14340

版本

  1. v1当前

前言:据说 CSP 前发题解会 ++RP。

题意

有 nn 个二元组 (x,y)(x,y) 和 qq 个询问 (A,B,C)(A,B,C),每个询问求满足 x≥Ax\ge A,y≥By\ge B,x+y≥Cx+y\ge C 的二元组个数。

1≤n,q≤1051 \le n,q \le 10^5。

思路

cdq 分治裸题。不会三维偏序出门左转 P3810。

注意到前两者满足偏序关系,故想到 cdq 分治。令 zi←xi+yiz_i \gets x_i + y_i,问题转化为求满足 xi≥Ax_i \ge A,yi≥By_i \ge B,zi≥Cz_i \ge C 的对数。三维偏序即可。

时间复杂度 O(nlog⁡2n)\mathcal{O}(n \log^2n)。

注意:去重时注意数组越界问题。

代码

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int n, m, ans[N >> 1], tr[N];
vector<int> v;
struct node {
    int a, b, c, id, cnt;
    bool operator== (const node &x) const {
        return (a == x.a && b == x.b && c == x.c);
    }
} a[N], tmp[N];
bool cmp(const node &x, const node &y) {
    return (x.a ^ y.a) ? x.a > y.a : (x.b ^ y.b) ? x.b > y.b : x.id < y.id;
}
#define lowbit(x) (x & -x)
inline void add(int x, int d) {
    for(; x < N; x += lowbit(x)) tr[x] += d;
}
inline int qry(int x) {
    int res = 0;
    for(; x; x -= lowbit(x)) res += tr[x];
    return res;
}
void cdq(int L, int R) {
    if(L == R) return;
    int M = (L + R) >> 1;
    cdq(L, M), cdq(M + 1, R);
    int i = L, j = M + 1;
    for(; j <= R; ++j) {
        while(i <= M && a[i].b >= a[j].b) {
            if(!a[i].id) add(a[i].c, a[i].cnt);
            ++i;
        }
        if(a[j].id) ans[a[j].id] += qry(N - 1) - qry(a[j].c - 1);
    }
    for(--i; i >= L; --i) if(!a[i].id) add(a[i].c, -a[i].cnt);
    i = L, j = M + 1;
    int k = L;
    while(i <= M && j <= R)
        if(a[i].b >= a[j].b) tmp[k++] = a[i++];
        else tmp[k++] = a[j++];
    while(i <= M) tmp[k++] = a[i++];
    while(j <= R) tmp[k++] = a[j++];
    for(int i = L; i <= R; ++i) a[i] = tmp[i];
}
signed main() {
    cin.tie(0), cout.tie(0) -> sync_with_stdio(0);
    cin >> n >> m;
    for(int i = 1; i <= n; ++i)
        cin >> tmp[i].a >> tmp[i].b, tmp[i].id = 0, tmp[i].c = tmp[i].a + tmp[i].b,
        v.emplace_back(tmp[i].c);
    for(int i = 1; i <= m; ++i)
        cin >> a[i].a >> a[i].b >> a[i].c, a[i].id = i, v.emplace_back(a[i].c);
    sort(v.begin(), v.end()), v.erase(unique(v.begin(), v.end()), v.end());
    sort(tmp + 1, tmp + n + 1, cmp);
    int tot = 0;
    for(int i = 1, j; i <= n; ++i) {
        ++tot, j = 1;
        while(i < n && tmp[i] == tmp[i + 1]) ++i, ++j;
        a[m + tot] = tmp[i], a[m + tot].cnt = j;
    }
    for(int i = 1; i <= m + tot; ++i) a[i].c = lower_bound(v.begin(), v.end(), a[i].c) - v.begin() + 1;
    sort(a + 1, a + m + tot + 1, cmp);
    cdq(1, m + tot);
    for(int i = 1; i <= m; ++i)
        cout << ans[i] << '\n';
    return 0;
}
原文