HDOJ-1232(并查集)

路径压缩非递归版:


#include 

int N, M;
int set[1000];

int Find(int x)
{
    int y = x, t;
    while(set[y] != y) y = set[y];
    while(x != y){
        t = set[x];
        set[x] = y;
        x = t;
    }
    return x;
}
void Union(int x, int y)
{
    int px = Find(x), py = Find(y);
    if(px != py) set[px] = py;
}

int main()
{
    int i, x, y;
    while(scanf("%d", &N), N){
        scanf("%d", &M);
        for(i = 1; i <= N; ++i) set[i] = i;
        for(i = 0; i < M; ++i){
            scanf("%d %d", &x, &y);
            Union(x, y);
        }
        for(x = 0, i = 1; i <= N; ++i){
 
  

再复习下递归版的路径压缩:

#include 

int N, M;
int set[1000];

int Find(int x)
{
    return set[x] != x ? set[x] = Find(set[x]) : x;
}
void Union(int x, int y)
{
    int px = Find(x), py = Find(y);
    if(px != py) set[px] = py;
}

int main()
{
    int i, x, y;
    while(scanf("%d", &N), N){
        scanf("%d", &M);
        for(i = 1; i <= N; ++i) set[i] = i;
        for(i = 0; i < M; ++i){
            scanf("%d %d", &x, &y);
            Union(x, y);
        }
        for(x = 0, i = 1; i <= N; ++i){
            if(set[i] == i) ++x;
        }
        printf("%d\n", x - 1);
    }
    return 0;
}


            if(set[i] == i) ++x;
        }
        printf("%d\n", x - 1);
    }
    return 0;
}
发现无论是空间还是时间上递归版的都不比非递归版的差,而且递归版的路径压缩比非递归版的更好理解+代码量更少,以后果断还是优先选择递归版的呀

你可能感兴趣的:(每天A一道题,并查集)