跳到正文

题解

P2163——树状数组&&二维数点问题

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

文章信息

发布
2025年10月30日
收录
2026年1月2日
更新
2026年11月6日
篇幅
约 5 分钟
题目
P2163

版本

  1. v1当前

传送门:https://www.luogu.com.cn/problem/P2163

1.简要分析:

根据分析,得出此题是经典的二维数点问题,那么我们很容易便剖出了经典模型&&经典问题

再看数据范围,发现由于x,y的坐标数据范围过大,考虑离散化

其次,二维数点,很容易想到一个思路:二维前缀和,再其次,由于要适应离散化的需求,离线处理

最后一点细节,二维前缀和需要四个点,将每个询问矩形分成四个点加入,统一离散化

2.深入分析:

继续分析,根据上面的简要分析,我们离散化了x坐标,那么统计有多少个点在此点与(0,0)所围成矩形里,只需要判断在先前加入点中,有多少个点的y坐标比这个点的y坐标小就行了,也就是说,我们只需要考虑y坐标,单点修改,区间询问,考虑树状数组,然后此题就只剩下了代码实现难度

3.代码实现:

C++
#include<bits/stdc++.h>
using namespace std;
#define endl "\n"
#define cfalse cin.tie(0)->sync_with_stdio(0)
const int maxn = 3e6 + 5;
int tree[maxn];
int n, m;
int lowbit(int x){
    return x & (-x);
}
struct node{
    int x, y;
    int op;//-1: 树点 || 对于询问点,op代表第几个询问
    int op1;//-1:树点 || 1:左下,2:左上,3:右下,4:右上
};
struct node1{
    int y, id, op;//y坐标,第几个点,是否是树点? 0:树点,1:询问点
};
vector<node1>arr;//y坐标离散化数组
vector<node>mp;
int qr[maxn][10];//询问统计数组
void answer(){
    for(int i = 0; i < m; i++){
        cout << qr[i][4] + qr[i][1] - qr[i][2] - qr[i][3] << endl;
    }
}
//矩形面积 = S (c,d) + S (a−1,b−1) - S (a−1,d) - S (c,b−1)二维前缀和公式
bool cmp(node a, node b){//x坐标离散化
    if(a.x == b.x){//x坐标相同,树点优先,都是树点,y坐标小的优先
        return a.op == b.op ? a.y < b.y : a.op < b.op;
    }
    return a.x < b.x;
}
bool cmp1(node1 a, node1 b){//y坐标离散化
    if(a.y == b.y){
        return a.op < b.op;//若y坐标相同,树点优先
    }
    return a.y < b.y;
}
void add(int x){
    for(int i = x; i <= arr.size(); i += lowbit(i)){
        tree[i]++;
    }
}
int query(int x){
    int ans = 0;
    if(x == 0){
        return 0;
    }
    while(x > 0){
        ans += tree[x];
        x -= lowbit(x);
    }
    return ans;
}
signed main(){
    cfalse;
    cin >> n >> m;
    for(int i = 1; i <= n; i++){
        int x, y;
        cin >> x >> y;
        x++,y++;//为了防止-1这种情况,将x,y++,下面abcd处理同
        mp.push_back({x, y, -1, -1});
    }
    for(int i = 0; i < m; i++){
        int a, b, c, d;
        cin >> a >> b >> c >> d;
        a++,b++,c++,d++;
        mp.push_back({c, d, i, 4});
        mp.push_back({a - 1, b - 1, i, 1});
        mp.push_back({a - 1, d, i, 2});
        mp.push_back({c, b - 1, i, 3});
    }
    sort(mp.begin(), mp.end(), cmp);//x坐标离散化
    for(int i = 0; i < mp.size(); i++){
        arr.push_back({mp[i].y, i, (mp[i].op >= 0)});
    }
    sort(arr.begin(), arr.end(), cmp1);//y坐标离散化
    for(int i = 0; i < arr.size(); i++){
        mp[arr[i].id].y = i + 1;
    }
    for(auto i : mp){
        if(i.op == -1){
            add(i.y);
        }else{
            qr[i.op][i.op1] = query(i.y);
        }
    }
    answer();
    return 0;
}

适合写写训练代码能力

原文