并查集

来源:互联网 发布:linux svn 创建分支 编辑:程序博客网 时间:2024/06/07 00:36
#include <iostream>#include <string.h>#include <algorithm>#include <stdio.h>#include <math.h>#include <queue>#define MAXN 100010#define inf 0x3f3f3f3fusing namespace std;int uset[MAXN];int deep[MAXN];//深度void init(){    for(int i = 0; i < MAXN; ++i){        uset[i] = i;    }    memset(deep,0,sizeof(deep));}int found(int x){    return x==uset[x]?x:uset[x] = found(uset[x]);}int main(){    int n,m;    int x,y;    while(~scanf("%d",&n)){        init();        scanf("%d",&m);        while(m--){            scanf("%d%d",&x,&y);            int xx = found(x);            int yy = found(y);            if(xx != yy){                uset[xx] = yy;                /*加个深度优化                if(deep[xx] > deep[yy]){                    uset[y] = x;                }                else{                    uset[x] = y;                    if(deep[xx] == deep[yy]){                        ++deep[yy];                    }                }                */            }        }        for(int i = 1; i <= n; ++i){            x = found(i);            cout<<x<<endl;        }    }    return 0;}

0 0
原创粉丝点击