An earthquake takes place in Southeast Asia. The ACM (Asia Cooperated Medical team) have set up a wireless network with the lap computers, but an unexpected aftershock attacked, all computers in the network were all broken. The computers are repaired one by one, and the network gradually began to work again. Because of the hardware restricts, each computer can only directly communicate with the computers that are not farther than d meters from it. But every computer can be regarded as the intermediary of the communication between two other computers, that is to say computer A and computer B can communicate if computer A and computer B can communicate directly or there is a computer C that can communicate with both A and B.
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 4
FAIL SUCCESS
思路:(代码优化了一下降到一秒多跑完,有点慢哦) 并查集+点点距,详看代码;
#include<stdio.h>
int pre[1010],x[10010],y[10010];
int find(int t)
{
int r=t;
while(r!=pre[r])
r=pre[r];
int i=t,j;
while(i!=r)
{
j=pre[i];
pre[i]=r;
i=j;
}
return r;
}
int main()
{
int n,k,m,d,i,p1,p2;
char s[10];
scanf("%d %d",&n,&d);
for(i=1;i<=n;i++)
{
scanf("%d %d",&x[i],&y[i]);
pre[i]=0;//真假值区分是否修复过i号计算机;
}
while(~scanf("%s",s))
{
if(s[0]=='O')
{
scanf("%d",&k);
if(!pre[k])//表示k号计算机被修复;
pre[k]=k;
for(i=1;i<=n;i++)//把所有的计算机遍历一遍,找出与其距离小于d并且修复过的计算机,合并成一个集合;
{
m=(x[i]-x[k])*(x[i]-x[k])+(y[i]-y[k])*(y[i]-y[k]);//点点距;
if(pre[i] && m<=d*d)
{
int fx=find(i);
int fy=find(k);
if(fx!=fy)
pre[fx]=fy;
}
}
}
else
{
scanf("%d %d",&p1,&p2);
if(pre[p1] && pre[p2] && find(p1)==find(p2))//避免S 1 1 这个数据,要查看p1,p2是否被修复;
printf("SUCCESS\n");
else printf("FAIL\n");
}
}
return 0;
}