标签:
以下是两种实现:
// Model One const int MAXSIZE = 500010; int rank[MAXSIZE]; // 节点高度的上界 int parent[MAXSIZE]; // 根节点 int FindSet(int x){ // 查找+递归的路径压缩 if( x != parent[x] ) parent[x] = FindSet(parent[x]); return parent[x]; } void Union(int root1, int root2){ int x = FindSet(root1), y = FindSet(root2); if( x == y ) return ; if( rank[x] > rank[y] ) parent[y] = x; else{ parent[x] = y; if( rank[x] == rank[y] ) ++rank[y]; } } void Initi(void){ memset(rank, 0, sizeof(rank)); for( int i=0; i < MAXSIZE; ++i ) parent[i] = i; }
// Model Two const int MAXSIZE = 30001; int pre[MAXSIZE]; //根节点i,pre[i] = -num,其中num是该树的节点数目; //非根节点j,pre[j] = k,其中k是j的父节点 int Find(int x){ //查找+非递归的路径压缩 int p = x; while( pre[p] > 0 ) p = pre[p]; while( x != p ){ int temp = pre[x]; pre[x] = p; x = temp; } return x; } void Union(int r1, int r2){ int a = Find(r1); int b = Find(r2); if( a == b ) return ; //加权规则合并 if( pre[a] < pre[b] ){ pre[a] += pre[b]; pre[b] = a; } else { pre[b] += pre[a]; pre[a] = b; } } void Initi(void){ for( int i=0; i < N; ++i ) pre[i] = -1; }
标签:
原文地址:http://blog.csdn.net/ljlstart/article/details/51348393