题目大意:有n台电脑,因为某些原因只能在d距离内进行交流,输入n台电脑的坐标判断能否连接。
思路:建立并查集两个基本函数“查找”“合并”,用use数组存储能电脑是否修好。合并的条件是电脑之间距离是否为 <= d
#include<stdio.h>
#include<string.h>
#define M 1010
bool use[M];
int distance;
struct Node
{
int x,y;
int father;
}node[M];
int Find_it(int x) //这个虽然代码变长但是时间,变短了
{
int temp = x,t;
while(temp != node[temp].father)
temp = node[temp].father;
while(x != node[x].father){
t = node[x].father;
node[x].father = temp;
x = t;
}
return temp;
}
void Union(const Node n1,const Node n2)
{
int root1 = Find_it(n1.father);
int root2 = Find_it(n2.father);
if(root1 != root2)
if((n1.x - n2.x) * (n1.x - n2.x) + (n1.y - n2.y) * (n1.y - n2.y) <= distance * distance)
node[root2].father = root1;
}
int main()
{
// freopen("input.txt","r",stdin);
int computers,repire,i,from,to;
char c;
scanf("%d%d",&computers,&distance);
memset(use,false,sizeof(use));
for(i = 1;i <= computers; i++)
node[i].father = i;
for(i = 1;i <= computers; i++)
scanf("%d%d",&node[i].x,&node[i].y);
while(scanf("\n%c",&c) != EOF){
if(c == 'O'){
scanf("%d",&repire);
use[repire] = true;
for(i = 1;i <= computers; i++)
if(use[i] && i != repire)
Union(node[i],node[repire]); //遍历找满足条件的就合并
}
else {
scanf("%d%d",&from,&to);
if(Find_it(from) == Find_it(to))
printf("SUCCESS\n");
else printf("FAIL\n");
}
}
return 0;
}
#include<stdio.h>
#include<string.h>
#define M 1010
bool use[M];
int distance;
struct Node
{
int x,y;
int father;
}node[M];
int Find_it(int x) //递归虽然代码变短但是时间变短长了
{
return x == node[x].father ? x : Find_it(node[x].father);
}
void Union(const Node n1,const Node n2)
{
int root1 = Find_it(n1.father);
int root2 = Find_it(n2.father);
if(root1 != root2)
if((n1.x - n2.x) * (n1.x - n2.x) + (n1.y - n2.y) * (n1.y - n2.y) <= distance * distance)
node[root2].father = root1;
}
int main()
{
// freopen("input.txt","r",stdin);
int computers,repire,i,from,to;
char c;
scanf("%d%d",&computers,&distance);
memset(use,false,sizeof(use));
for(i = 1;i <= computers; i++)
node[i].father = i;
for(i = 1;i <= computers; i++)
scanf("%d%d",&node[i].x,&node[i].y);
while(scanf("\n%c",&c) != EOF){
if(c == 'O'){
scanf("%d",&repire);
use[repire] = true;
for(i = 1;i <= computers; i++)
if(use[i] && i != repire)
Union(node[i],node[repire]); //遍历找满足条件的就合并
}
else {
scanf("%d%d",&from,&to);
if(Find_it(from) == Find_it(to))
printf("SUCCESS\n");
else printf("FAIL\n");
}
}
return 0;
}