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
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
直接上代码
#include<iostream>
#include<cmath>
using namespace std;
int father[1010];
bool work[1010];
struct{
int x,y;
}e[1010];
int find(int x)
{
while(x!=father[x])x=father[x];
return x;
}
void merge(int x,int y)
{
x=find(x);
y=find(y);
if(x!=y)father[y]=x;
}
int main()
{
int n,d;
cin>>n>>d;//n是电脑数,d是最大距离
for(int i=1;i<=n;i++)
{
work[i]=0;
father[i]=i;
cin>>e[i].x>>e[i].y;
}
char q;
while(cin>>q){
if(q=='S')
{
int a,b;
cin>>a>>b;
if(find(a)==find(b))cout<<"SUCCESS"<<endl;
else cout<<"FAIL"<<endl;
}
else
{
int a;
cin>>a;
work[a]=1;
for(int i=1;i<=n;i++)
{
if(i==a)continue;
if(work[i]&&sqrt((e[i].x-e[a].x)*
(e[i].x-e[a].x)+(e[i].y-e[a].y)*(e[i].y-e[a].y))<=d)
merge(i,a);
}
}
}
return 0;
}
这是没有任何优化 的并查集
下面是优化后的(路径压缩+按秩合并)
#include<iostream>
#include<cmath>
using namespace std;
int father[1010],rank[1010];
bool work[1010];
struct{
int x,y;
}e[1010];
int find(int x)
{
int r=x;
while(r!=father[r])r=father[r];
int i=x,j;
while(i!=r){
j=father[i];
father[i]=r;
i=j;
}
return r;
}
void merge(int x,int y)
{
x=find(x);
y=find(y);
if(x!=y)
{
if(rank[x]>rank[y])father[y]=x;
else
{
father[x]=y;
if(rank[x]==rank[y])rank[y]++;
}
}
}
int main()
{
int n,d;
cin>>n>>d;//n是电脑数,d是最大距离
for(int i=1;i<=n;i++)
{
work[i]=0;
rank[i]=0;
father[i]=i;
cin>>e[i].x>>e[i].y;
}
char q;
while(cin>>q){
if(q=='S')
{
int a,b;
cin>>a>>b;
if(find(a)==find(b))cout<<"SUCCESS"<<endl;
else cout<<"FAIL"<<endl;
}
else
{
int a;
cin>>a;
work[a]=1;
for(int i=1;i<=n;i++)
{
if(i==a)continue;
if(work[i]&&sqrt((e[i].x-e[a].x)*
(e[i].x-e[a].x)+(e[i].y-e[a].y)*(e[i].y-e[a].y))<=d)
merge(i,a);
}
}
}
return 0;
}
个人觉得优化后时间并没有差很远,优化后是8469ms,优化前8813ms。
但是万一题目要是卡时间,所以优化是有必要的。