POJ2236 并查集灵活运用
http://poj.org/problem?id=2236
关键点在于用并查集实现两个网络是否连通的查询
每次在修过的电脑的时候把每台电脑路径小于d的都合并一遍 这样子查询就方便了。
#include <iostream>
#include <math.h>
using namespace std;
int n;
double d;
struct{
int x,y;
}arr[1005];
int f[1005];
bool repair[1005];
int find(int x){
if(f[x] == x){
return x;
}else{
return f[x] = find(f[x]);
}
}
void merge(int x,int y){
int a = find(x);
int b = find(y);
if(a == b){
return;
}
f[b] = a;
}
double dis(int a,int b){
int x1 = arr[a].x;
int y1 = arr[a].y;
int x2 = arr[b].x;
int y2 = arr[b].y;
return sqrt(double(pow(x1-x2, 2) + pow(y1-y2, 2)));
}
int main(int argc, char** argv) {
cin >> n >> d;
for(int i = 1; i<=n; i++){
cin >> arr[i].x >> arr[i].y;
f[i] = i;
}
char c;
while(cin >> c){
if(c == 'O'){
int j;
cin >> j;
repair[j] = true;
for(int i = 1; i<=n; i++){
if(i == j){
continue;
}
if(!repair[i]){
continue;
}
if(dis(i, j) > d){
continue;
}
merge(i, j);
}
}else if(c == 'S'){
int a,b;
cin >> a >> b;
if(find(a) == find(b)){
cout << "SUCCESS" << endl;
}else{
cout << "FAIL" << endl;
}
}
}
return 0;
}