跳到正文

题解

题解:P5193 [TJOI2012] 炸弹

koukou约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年10月30日
收录
2026年11月1日
更新
2026年11月9日
篇幅
约 3 分钟
获赞
1
题目
P5193

版本

  1. v1当前

简单题。

把坐标系旋转 4545 度,即转化为切比雪夫距离,公式上是 (x,y)→(x−y,x+y)(x,y)\to(x-y,x+y),于是每一个点覆盖的位置变成了一个正方形,半径为 rr。求有多少个连通块。

考虑扫描线,并查集维护连通块。

用一个 set 维护所有横坐标在 [x−r,x][x-r,x] 内的点的 yy 值,查询的时候只查询纵坐标在这里的前驱后继,连接这两对点即可。

只连接两个是对的,因为更远的会通过前驱后继传递得到。

Code
C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5 + 5;
int n, R, ans;
struct DSU
{
    int fa[N];
    void init()
    {
        iota(fa + 1, fa + n + 1, 1);
        return;
    }
    int find(int x)
    {
        if(fa[x] == x) return x;
        return fa[x] = find(fa[x]);
    }
    bool merge(int x, int y)
    {
        x = find(x), y = find(y);
        if(x == y) return 0;
        fa[x] = y;
        return 1;
    }
}dsu;
struct Node
{
    int x, y, id;
}a[N];
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    // freopen(".in", "r", stdin);
    // freopen(".out", "w", stdout);
    cin >> n >> R;
    ans = n, dsu.init();
    for(int i = 1, x, y; i <= n; i++) cin >> x >> y, a[i] = {x - y, x + y, i};
    sort(a + 1, a + n + 1, [](const Node &x, const Node &y)
    {
        return x.x < y.x;
    });
    set<pair<int, int>> st;
    for(int l = 1, r = 1; r <= n; r++)
    {
        while(l < r && a[r].x - a[l].x > R) st.erase({a[l].y, a[l].id}), l++;
        auto it = st.lower_bound({a[r].y, -1});
        if(it != st.end() && it -> first - a[r].y <= R) ans -= dsu.merge(a[r].id, it -> second);
        if(it != st.begin()) 
        {
            it = prev(it);
            if(a[r].y - it -> first <= R) ans -= dsu.merge(a[r].id, it -> second);
        }
        st.insert({a[r].y, a[r].id});
    }
    cout << ans;
    return 0;
}
原文