题解:P14213 [COI 2010] 橡树 / HRASTOVI

比较模板的离散化

使用两个 map<int, vector<int>>

  • a[y]:存储所有纵坐标为 \(y\) 的点的横坐标列表

  • b[x]:存储所有横坐标为 \(x\) 的点的纵坐标列表

读入所有点后,对每个 vector 排序,以便二分查找。

定义函数 \(f(v, l, r)\),返回数组中值在闭区间 \([l, r]\) 内的元素个数。使用二分查找实现。

对于每个矩形,下边界为 \(f(a[y_1], x_1, x_2)\),上边界为 \(f(a[y_2], x_1, x_2)\),左边界为 \(f(b[x_1], y_1 + 1, y_2 - 1)\),右边界为 \(f(b[x_2], y_1 + 1, y_2 - 1)\)

将四个结果相加即为答案。

代码:

#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
int n;
map<int, vector<int> > a, b;
int f(vector<int> &v, int x, int y) {
    if (x > y) {
        return 0;
    }
    return upper_bound(v.begin(), v.end(), y) - lower_bound(v.begin(), v.end(), x);
}
signed main() {
    cin >> n;
    for (int i = 1; i <= n; i++) {
        int x, y;
        cin >> x >> y;
        a[y].push_back(x);
        b[x].push_back(y);
    }
    for (auto &v : a) {
        sort(v.second.begin(), v.second.end());
    }
    for (auto &v : b) {
        sort(v.second.begin(), v.second.end());
    }
    int que;
    cin >> que;
    for (int i = 1; i <= que; i++) {
        int x_1, y_1, x_2, y_2;
        cin >> x_1 >> y_1 >> x_2 >> y_2;
        int ans = 0;
        ans += f(a[y_1], x_1, x_2);
        ans += f(b[x_1], y_1 + 1, y_2 - 1);
        ans += f(a[y_2], x_1, x_2);
        ans += f(b[x_2], y_1 + 1, y_2 - 1);
        cout << ans << endl;
    }
    return 0;
}
posted @ 2026-03-12 13:00  Python_enjoy  阅读(2)  评论(0)    收藏  举报