Educational Codeforces Round 124 (Rated for Div. 2)D. Nearest Excluded Points 曼哈顿距离,二维,bfs

该文章讲述了如何在CodeforcesProblem-1651D中利用BFS策略寻找每个点的最近邻点,以及如何处理大规模数据下的空间优化。
摘要由CSDN通过智能技术生成

Problem - 1651D - Codeforces

目录

题意:

思路:

参考代码:


题意:

给你一些点,找到离这些每个点的一个最近的点。

(而且要一一对应,,)

思路:

样例一:

边缘点的邻点就是最近的,对里面的点来说也是。

对边缘的点bfs搜里面的点即可。处理对应比较麻烦,需多开空间。

(题目有给边界哦;1e6开不了二维,只能用pair压缩了(类似邻接表))

参考代码:

我是用map记录给定点的初始下标,方便最后给答案。

barr就是"visit"数组,是否bfs过。

bfs带的第二个pair就是边缘点坐标。

#define ll long long
#define endl "\n"
//#define int long long
#define PII pair<int,int>
const ll inf = 1e9;
const ll MOD = 0x77777777737;
const int maxn = 1e6;
 
int fx[4] = {1,-1,0,0};
int fy[4] = {0,0,1,-1};
 
void solve()
{
	int n;
	cin >> n;
	map<PII,int>arr;
	vector<int>barr(n);
	int a, b;
	for (int i = 0; i < n; i++)
	{
		cin >> a >> b;
		arr[{ a,b }] = i;
	}
	vector<PII>aim;
	vector<PII>ans(n);
	for (auto x:arr)
	{
		for (int j = 0; j < 4; j++)
		{
			a = x.first.first + fx[j], b = x.first.second + fy[j];
			if (a >= 0 && a <= maxn
				&& b >= 0 && b <= maxn && !arr.count({a,b}))
			{
				aim.push_back({ a,b });
				break;
			}
		}
	}
	//向内bfs
	queue<pair<PII,PII>>bfs;
	for (int i = 0; i < aim.size(); i++)
	{
		bfs.push({ aim[i],aim[i] });
	}
	while (bfs.size())
	{
		int c = bfs.front().second.first ,d= bfs.front().second.second;
		for (int j = 0; j < 4; j++)
		{
			a = bfs.front().first.first + fx[j], b = bfs.front().first.second + fy[j];
			if (a >= 0 && a <= maxn
				&& b >= 0 && b <= maxn && arr.count({ a,b }))
			{
				if (barr[arr[{a, b}]] == 0)
				{
					barr[arr[{a, b}]] = 1;
					bfs.push({ {a,b} ,{c,d} });
					ans[arr[{a, b}]] = { c,d };
				}
			}
		}
		bfs.pop();
	}
	
	for (auto x : ans)
	{
		cout << x.first << " " << x.second << endl;
	}
}
signed main()
{
	
	ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	int t = 1;
	//cin >> t;
	while (t--)
	{
		solve();
	}
	return 0;
}

  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值