Nearest Excluded Points(BFS/技巧/连通块)

题目
题意:给定 n n n个整数点 x i , y i ( 1 < = x i , y i < = 2 ∗ 1 0 5 ) x_i,y_i(1<=x_i,y_i<=2*10^5) xi,yi(1<=xi,yi<=2105),现在求出每个点对应的最近点(曼哈顿距离),要求这些最近点不能在这 n n n个点中。

参考

思路:直接暴搜,会T到家。
换个思路,对于这 n n n个点(便于区分,称它们为有效点),我们发现,对于有效点 x x x,除非周围都被其他有效点包围,否则它的exclueded point只要取它周边的相连的非有效点即可,此时距离最小。
那么对于剩下那些被其他有效点包围的 有效点,我们怎么求它的exclueded point呢?我们bfs搜索它四周的有效点即可。

通过这种方式,bfs搜索的范围被限制在相邻的点中,搜索范围就得到限制了。
代码

#include<bits/stdc++.h>
using namespace std;

int dx[] = {0, 0, -1, 1};
int dy[] = {-1, 1, 0, 0};

int main() {
    
    int n;
    scanf("%d", &n);
    vector<pair<int, int>> a(n);
    for (auto &v : a) scanf("%d %d", &v.first, &v.second);
    
    set<pair<int, int>> st(a.begin(), a.end());
    map<pair<int, int>, pair<int, int>> ans;
    queue<pair<int, int>> q;
    for (auto v : a) {
    	int x = v.first, y = v.second;
        for (int i = 0; i < 4; ++i) {
            int nx = x + dx[i], ny = y + dy[i];
            if (st.count({nx, ny})) {
                continue;
            }
            ans[{x, y}] = {nx, ny};
            q.push({x, y});
            break;
        }
    }
    
    while (!q.empty()) {
        int x = q.front().first, y = q.front().second;
        q.pop();
        for (int i = 0; i < 4; ++i) {
            int nx = x + dx[i], ny = y + dy[i];
            if (!st.count({nx, ny}) || ans.count({nx, ny})) {
                continue;
            }
            ans[{nx, ny}] = ans[{x, y}];
            q.push({nx, ny});
        }
    }
    
    for (auto v : a) {
        auto it = ans[{v.first, v.second}];
        printf("%d %d\n", it.first, it.second);
    }
    
    return 0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值