题目链接:
POJ 2236 Wireless Network
题意:有N台损坏了电脑,给出N台电脑的坐标,已知当两个修好的电脑间的距离小于等于d时,两台修好的电脑可以连通。
两台连通的电脑之间可以有若干台电脑作为桥梁。
有两种操作:O,P:修好第P台电脑
S P,Q:询问第P台电脑和第Q台电脑是否连通。
对于每一条询问如果连通输出“SUCCESS”,未连通输出“FAIL”。
分析:
把互相连通的电脑放在一个“集合”,即有相同的公共祖先,然后对于每一条查询,只需判断公共祖先是否相同即可。
注意:
dis[i][j]表示第i台电脑和第j台电脑之间直线距离,如果直接计算距离的话会因为精度问题WA.
不妨直接令dis[i][j]=距离^2,然后在mix里直接比较dis[i][j]和d*d即可。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 1010;
int n, d, p, q, xx, yy;
int pre[maxn], vis[maxn];
int dis[maxn][maxn];
char s[5];
struct Point {
int x, y;
}point[maxn];
int Distance(struct Point a, struct Point b)
{
return ((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
}
int find(int x)
{
int r = x;
while (pre[r] != r)//找到根结点
r = pre[r];
int i = x, j;
while (pre[i] != r)
{
j = pre[i];
pre[i] = r;
i = j;
}
return r;
}
void mix(int x, int y)
{
int fx = find(x);
int fy = find(y);
if (fx != fy && dis[x][y] <= d * d )//不是dis[fx][fy]<=d
{
pre[fy] = fx;
}
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
#endif
while (~scanf("%d%d", &n, &d))
{
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= n; i++)
pre[i] = i;
for (int i = 1; i <= n; i++)
scanf("%d%d", &point[i].x, &point[i].y);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j) dis[i][j] = 0;
else dis[i][j] = Distance(point[i], point[j]);
}
}
while (~scanf("%s", s))
{
if (s[0] == 'O')
{
scanf("%d", &p);
vis[p] = 1;//p已经修好了
for (int i = 1; i <= n; i++)
if (vis[i] && i != p) mix(i, p);//将已经修好的合并
}
else if (s[0] == 'S')
{
scanf("%d%d", &p, &q);
//for (int i = 1; i <= n;i++)
// printf("pre[%d]=%d \n", i, pre[i]);
if (find(p) == find(q)) printf("SUCCESS\n");
else printf("FAIL\n");
}
}
}
return 0;
}