这道题用到了并查集,给出了n台电脑的坐标。如果想让2台电脑相互通信,需要这2台电脑的距离小于一定的数值,或者可以通过第三台电脑间接通信,甚至通过n台电脑间接通信。因此,只要2台电脑的距离满足,就把2台电脑加入到同一个集合内。最后给出2台电脑,判断这2台电脑之间是否可以相互通信。
#include <iostream>
#include <cmath>
using namespace std;
int set[1010];
struct point{
int x;
int y;
}post[1010];
int book[1010];
int d;
bool distance_count(int a, int b)
{
double k1 = post[a].x - post[b].x;
double k2 = post[a].y - post[b].y;
if (pow(k1, 2) + pow(k2, 2) > pow(d, 2))
return false;
else
return true;
}
int search(int i)
{
if (i == set[i])
return i;
else
return set[i] = search(set[i]);
}
void hebing(int a, int b)
{
int l1 = search(a);
int l2 = search(b);
if (l1 != l2)
set[l1] = l2;
}
int main()
{
int n;
int i;
char mingling;
cin >> n >> d;
for (i = 1; i <= n; i++)
{
book[i] = 0;
set[i] = i;
cin >> post[i].x >> post[i].y;
}
while (cin >> mingling)
{
if (mingling == 'O')
{
int k;
cin >> k;
book[k] = 1;
for (i = 1; i <= n; i++)
{
if (i != k&&book[i] && distance_count(i, k))
hebing(i,k);
}
}
if (mingling == 'S')
{
int k1, k2;
cin >> k1 >> k2;
if (search(k1) != search(k2))
cout << "FAIL" << endl;
else
cout << "SUCCESS" << endl;
}
}
return 0;
}