Wireless Network POJ - 2236

WA了一发,要注意合并节点a到集合b的时候,要将a的整棵树都合并到b,而不是仅仅把a的父节点设置为b的父节点

#include
#include
using namespace std;
const int MAXN = 1000 + 10;

int fa[MAXN];
int n, d;

struct Computer {
    int x, y;
    int statu;//是否修复
};
Computer coms[MAXN];

void init() {
    for(int i = 0; i <= n; ++i) {
        fa[i] = i;
    }
}

int find(int x) {
    return fa[x] == x ? x : fa[x] = find(fa[x]);//查找并缩短路径
}

int insert(int x) {
    for(int i = 1; i <= n; ++i) {//所有符合条件的电脑都合并到一起
        if(i != x && coms[i].statu == 1 && ((coms[i].x - coms[x].x) *(coms[i].x - coms[x].x)) + ((coms[i].y - coms[x].y) *(coms[i].y - coms[x].y)) <= d * d) {
            fa[find(x)] = find(i);//要注意是x所在的整棵树
        }
    }
}

int main() {


    memset(coms, 0, sizeof(coms));

    scanf("%d%d", &n, &d);
    init();
    for(int i = 1; i <= n; ++i) {
        scanf("%d%d", &coms[i].x, &coms[i].y);
    }
    char com[2];
    int x, y;
    while(scanf("%s", &com) == 1) {
        if(com[0] == 'O') {
            scanf("%d", &x);
            coms[x].statu = 1;
            insert(x);
        } else {
            scanf("%d%d", &x, &y);
            if(find(x) == find(y)) {
                printf("SUCCESS\n");
            } else {
                printf("FAIL\n");
            }
        }
    }
    return 0;
}


你可能感兴趣的:(并查集,数据结构)