原题链接:Problem - 1651D - Codeforces
题目大意:给你n个不同的二维坐标上的点,然后让你分别找到离各店曼哈顿距离最近的点,且这个点不在给你的n个点之中(如果有多个答案,随便写哪个点都行)。
思路:如果对每个点bfs,如果是个很密集的图,然后..就wa了。其实想想,很密集的时候,是不是有些点,从中间向外算的时候其实会重复访问查看很多点。我们知道最后找到的答案一定是这n个点上下左右空的点中的一个,所以我们可以提前把这n个点上下左右四个方向不在这n个点中的点加入队列,然后每次寻找这n个点中的点,如果找到了,可以把这个点加入队列,这样下次找就是找的距离为2的点...最后找到n个点就退出,每次把由哪个点来的(root)记录一下。
PII与map结合
感觉写的时候还是不太熟练,这个题得多些几次。
AC代码:
#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
typedef pair<int, int> PII;
const double pi = acos(-1.0);
#define rep(i, n) for (int i = 1; i <= (n); ++i)
#define rrep(i, n) for (int i = n; i >= (1); --i)
typedef long long ll;
#define sqar(x) ((x)*(x))
const int N = 2e5 + 10;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
int x[N], y[N];
int main()
{
int n;
map<PII, int> id, vis;
map<PII, PII> root;
queue<PII> q;
scanf("%d", &n);
rep(i, n)
{
scanf("%d %d", &x[i], &y[i]);
id[{x[i], y[i]}] = i;
}
rep(i, n)
for(int j = 0; j < 4; j++)
{
int xx = x[i] + dx[j], yy = y[i] + dy[j];
if(!id.count({xx, yy})) q.push({xx, yy}), root[{xx,yy}] = {xx, yy};
}
int cnt = 0;
while(q.size())
{
auto temp = q.front();
q.pop();
int x = temp.first, y = temp.second;
for(int i = 0; i < 4; i++)
{
int xx = x + dx[i], yy = y + dy[i];
if(id.count({xx, yy}) && !vis[{xx, yy}])
{
vis[{xx, yy}] = 1;
root[{xx, yy}] = root[{x, y}];
q.push({xx, yy});
cnt++;
}
}
if(cnt == n) break;
}
rep(i, n)
{
printf("%d %d\n", root[{x[i], y[i]}].first, root[{x[i], y[i]}].second);
}
return 0;
}
这题限制4s, 确实跑挺久:
参考大佬写的博客:「Codeforces」 Educataion Round #124 (Div. 2) A—D - AcWing
大佬注释写的很清楚~