并查集路径压缩

 1 //非递归压缩路径
 2 int findx(int x){
 3     int root = x;
 4     // 先找到根节点.
 5     while(root != parent[root])
 6         root = parent[root];
 7     while(x != root){
 8         int p = parent[x];
 9         parent[x] = root;  // 将x指向根节点.
10         x = p; // 移到x原来的父节点继续进行压缩.
11     }
12     return root;
13 }
14 
15 //回溯路径时压缩, 可能会造成堆栈溢出, 建议用上一种.
16 int findx(int x){
17     if(x!=parent[x]){
18         parent[x] = findx(parent[x]);
19     }
20     return parent[x];
21 }
原文地址:https://www.cnblogs.com/roger9567/p/4881341.html