Description
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.
Input
The first line contains two integers N and d (1 <= N <= 1001, 0 <= d <= 20000).Here N is the number of computers, which are numbered from 1 to N, and D is the maximum distance two computers can communicate directly. In the next N lines, each contains two integers xi, yi (0 <= xi, yi <= 10000), which is the coordinate of N computers. From the (N+1)-th line to the end of input, there are operations, which are carried out one by one. Each line contains an operation in one of following two formats:
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
For each Testing operation, print “SUCCESS” if the two computers can communicate, or “FAIL” if not.
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
题目分析
裸并查集。每次激活一点后遍历其他所有点,将已激活且与其距离不大于d的点unite即可。
注意读入scanf(" %c",&ch),在%c之前有一个空格,可以忽略空格和回车。
代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<climits>
#include<cstdlib>
#include<ctime>
using namespace std;
const int maxn=1e3+5;
int par[maxn],r[maxn];
bool f[maxn];
long long ax[maxn],ay[maxn];
int find(int x)
{
return (par[x]==x)?x:(par[x]=find(par[x]));
}
void unite(int x,int y)
{
x=find(x);
y=find(y);
if(x==y) return;
if(r[x]<r[y]) par[x]=y;
else
{
par[y]=x;
if(r[x]==r[y]) r[x]++;
}
}
int main()
{
int n,d;
cin>>n>>d;
d*=d;
for(int i=1;i<=n;i++) cin>>ax[i]>>ay[i];
memset(f,0,sizeof f);
memset(r,0,sizeof r);
for(int i=1;i<maxn;i++) par[i]=i;
char ch;
int p,q;
while(~scanf(" %c",&ch))
{
if(ch=='O')
{
scanf("%d",&p);
for(int i=1;i<=n;i++)
if(f[i]&&((ax[i]-ax[p])*(ax[i]-ax[p])+(ay[i]-ay[p])*(ay[i]-ay[p])<=d))
unite(p,i);
f[p]=true;
}
else if(ch=='S')
{
scanf("%d%d",&p,&q);
if(find(p)==find(q))
printf("SUCCESS\n");
else
printf("FAIL\n");
}
}
return 0;
}

本文探讨了一次地震导致的亚洲合作医疗团队无线网络崩溃后的修复过程,使用并查集算法解决网络节点间的直接通信问题。通过操作指令,逐步修复网络节点,实现节点间有效通信,最终网络恢复正常。
250

被折叠的 条评论
为什么被折叠?



