并查集(Union-Find)
Date:2019-06-23 13:42:53
1 //定义 2 int father[N]; //father[1]=2,即2是1的父亲,根结点用father[i]=i表示 3 4 //初始化 5 for(int i=1; i<=N; i++) 6 father[i]=i; //初始时有N个独立的集合 7 8 //查找 9 //对于给定的结点,寻找其根结点 10 int Find(int x) 11 { 12 if(father[x] == x) 13 return x; 14 Find(father[x]); 15 } 16 17 //合并 18 void Union(int a, int b) 19 { 20 int fa = Find(a); 21 int fb = Find(b); 22 father[fb] = fa; //不能用father[a]=b 23 Find2(b); //将fb中的结点更新至fa 24 } 25 26 27 //路径压缩 28 //把当前查询结点的路径上所有的结点的父亲都指向根结点 29 int Find2(int x) 30 { 31 int r = x; 32 while(x != father[x]) 33 x = father[x]; 34 //此处x已经是根结点 35 while(r != father[r]) 36 { 37 int z = r; 38 r = father[r]; 39 father[z] = x; 40 } 41 } 42 43 //递归写法 44 int Find2(int x) 45 { 46 if(x == father[x]) 47 return x; 48 fathre[x] = Find2(father[x]); 49 }