POJ-2236 Wireless Network(并查集)
In the process of repairing the network, workers can take two kinds of operations at every moment, repairing a computer, or testing if two computers can communicate. Your job is to answer all the testing operations.
1. "O p" (1 <= p <= N), which means repairing computer p.
2. "S p q" (1 <= p, q <= N), which means testing whether computer p and q can communicate.
The input will not exceed 300000 lines.
4 1 0 1 0 2 0 3 0 4 O 1 O 2 O 4 S 1 4 O 3 S 1 4Sample Output
FAIL SUCCESS
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
#define MAX 1020
int father[MAX],n;
struct point
{
double x;
double y;
}p[MAX];
int find(int x)
{
if(x==father[x])
return x;
return find(father[x]);
}
void Union(int x,int y)
{
int xn,yn;
xn=find(x);
yn=find(y);
if(xn!=yn)
father[yn]=xn;
}
double dis(point a,point b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
int main()
{
int i,x,y;
double d;
int cnt[MAX],num=1,n;
memset(cnt,0,sizeof(cnt));
for(i=1;i<MAX;i++)
father[i]=i;
char c[2]; //因为%s,要多留\0,char是不行的,因为后面有个空格,%s会根据他将其变为\0, %c,空格就会被下个整型吸收
scanf("%d%lf",&n,&d);
for(i=1;i<=n;i++)
scanf("%lf%lf",&p[i].x,&p[i].y);
while(scanf("%s",c)!=EOF)
{
if(c[0]=='O')
{
scanf("%d",&x);
for(i=1;i<num;i++)
{
if(dis(p[cnt[i]],p[x])<=d) //每次修一台电脑,就将其与之前所有电脑,看能否连接。
Union(cnt[i],x);
}
cnt[num++]=x; //cnt是记录维修好了的电脑。
}
if(c[0]=='S')
{
scanf("%d%d",&x,&y);
if(find(x)==find(y))
printf("SUCCESS\n");
else
printf("FAIL\n");
}
}
return 0;
}