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.
Input
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.
Output
Sample Input
4 1 0 1 0 2 0 3 0 4 O 1 O 2 O 4 S 1 4 O 3 S 1 4
Sample Output
FAIL SUCCESS
------AC------
用pos[][]记录坐标,book[]表示修复的计算机,fa[]建立树
#include<iostream>
#include<cstring>
using namespace std;
int book[1050],pos[1050][5],fa[1050],d;
int Find(int x)
{
if(fa[x]==x)
return x;
return fa[x]=Find(fa[x]);
}
void Mix(int x,int y)
{
int fx=Find(x),fy=Find(y);
if(fx>fy)
swap(fx,fy);
if(fx!=fy)
fa[fy]=fx;
}
bool dis(int x1,int y1,int x2,int y2)
{
int len=(x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);
if(len<=d*d)
return true;
return false;
}
int main()
{
int n,i,j;
memset(book,0,sizeof(book));
memset(pos,0,sizeof(pos));
for(i=0;i<1005;++i)
fa[i]=i;
cin>>n>>d;
//从第一台计算机开始记录比较方便,不然下面修复计算机时会混乱修复哪一台计算机
for(i=1;i<=n;++i)
cin>>pos[i][0]>>pos[i][1];
char ch;
int x1,x2,num=0;
//用C要注意回车键
while(cin>>ch>>x1)
{
if(ch==’O’)
{
for(i=0;i<num;++i)
{
// printf(“%d %d %d \n”,x1,book[i],dis(pos[book[i]][0],pos[book[i]][1],pos[x1][0],pos[x1][1]));
if(dis(pos[book[i]][0],pos[book[i]][1],pos[x1][0],pos[x1][1]))
Mix(x1,book[i]);
}
book[num++]=x1;
// for(i=0;i<num;++i)
// printf(“%d “,book[i]);
// printf(“\n”);
}
if(ch==’S’)
{
cin>>x2;
//这里是重点,用上面的方法将两棵树相连接,只有根节点的父亲改变,子节点的祖宗不变,所以要找真正的祖宗
while(fa[x1]!=x1)
x1=fa[x1];
while(fa[x2]!=x2)
x2=fa[x2];
if(x1==x2)
cout<<“SUCCESS”<<endl;
else
cout<<“FAIL”<<endl;
}
// for(i=0;i<10;++i)
// cout<<fa[i]<<” “;
// cout<<endl;
}
return 0;
}