1. 程式人生 > 實用技巧 >POJ 2236 Wireless Network 並查集

POJ 2236 Wireless Network 並查集

//並查集
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;

const int MAXN = 1e3+5;

int fa[MAXN], x[MAXN], y[MAXN]; //父結點 座標
int N, d;

int find(int x){
    if(x != fa[x])
        fa[x] = find(fa[x]);
    return fa[x];
}

void unite(int x, int y){
    int fx = find(x);
    int fy = find(y);
    fa[fx] = fy;
}

bool same(int x, int y){
    return find(x) == find(y);
}

int main(){
    cin >> N >> d;
    memset(fa, -1, sizeof fa);  // -1 表示損壞
    for(int i = 1; i <= N; i++) cin >> x[i] >> y[i];

    char c;
    while(~scanf("%c", &c)){
        int t, tt;
        scanf("%c", &c);
        if(c == 'O'){
            scanf("%d", &t);
            fa[t] = t;
            for(int i = 1; i <= N; i++)   //與其他在d內的結合
                if(fa[i] == -1) continue;
                else if((x[i]-x[t])*(x[i]-x[t])+(y[i]-y[t])*(y[i]-y[t]) <= d*d) unite(i, t);
        }
        else if(c == 'S'){
            scanf("%d %d", &t, &tt);
            if(fa[t] == -1 || fa[tt] == -1) printf("FAIL\n");
            else if(same(t, tt)) printf("SUCCESS\n");
            else printf("FAIL\n");
        }
    }
    //system("pause");
    return 0;
}