HDOJ-1213(并查集)

来源:互联网 发布:淘宝里卖家正在被处罚 编辑:程序博客网 时间:2024/06/05 10:17

基本的并查集应用


#include <stdio.h>#include <string.h>#define MAX 50001int father[MAX];int Find(int x){    return father[x] ? father[x] = Find(father[x]) : x;}int Union(int x, int y){    int fx = Find(x), fy = Find(y);    if(fx == fy) return fx;    else return father[fy] = fx;}int main(){    int test = 0, n, m;    int i, x, y, cnt;        scanf("%d", &test);    while(test--){        scanf("%d%d", &n, &m);        /* initialize */        memset(father, 0, sizeof(int) * (n + 1));        cnt = 0;        /* find and union */        for(i = 0; i < m; ++i){            scanf("%d%d", &x, &y);            Union(x, y);        }        /* count how many trees there are */        for(i = 1; i <= n; ++i){            if(Find(i) == i) ++cnt;/* if i is a root node */        }        printf("%d\n", cnt);    }        return 0;}


0 0
原创粉丝点击