正文
增加 6 行删除 5 行
91 行未改动9293949596979899100101102103104138 行未改动全部展开2432442452462472482492502512526 行未改动25926026126226326426526626711 行未改动91 行未改动于是我们现在有两种选择:1.将左树合并到右树上 2.将右树合并到左树上(两种都是可以的)以左树合并到右树上为例,我们只需修改 $parent$ 数组,让左树根结点指向右树根结点即可。不过在此之前,我们需要调用两次 $Find$ 函数以寻找 $5$ 和 $1$ 的父亲结点。```cpp line-numbers lines=4void Union(int x,int y){ //假设要合并x和y所在的集合int rootx=Find(x); //找x的父亲结点int rooty=Find(y); //找y的父亲结点parent[rootx]=rooty; //左树指向右树}```现在,我们就将左树成功合并到了右树上。但是合并后的树层数太多,所以我们需要对我们的 $Union$ 函数进行优化。138 行未改动全部展开parent[rootx]=rooty;}else{//两树等高parent[rooty]=rootx; //或parent[rootx]=rooty;parent[rootx]-=parent[rooty]; //因为是负数,-1就是绝对值+1//或parent[rooty]-=parent[rootx];}}void Union_size(int x,int y){ //按结点数合并示例,实际写的时候改为void Union(int x,int y);int rootx=Find(x);6 行未改动parent[rootx]=rooty;}else{//两树结点数相等parent[rooty]=rootx; //或parent[rootx]=rooty;parent[rootx]-=parent[rooty]; //因为是负数,-1就是绝对值+1//或parent[rooty]-=parent[rootx];}}```11 行未改动91 行未改动9293949596979899100101102103104105138 行未改动全部展开2442452462472482492502512522536 行未改动26026126226326426526626726811 行未改动91 行未改动于是我们现在有两种选择:1.将左树合并到右树上 2.将右树合并到左树上(两种都是可以的)以左树合并到右树上为例,我们只需修改 $parent$ 数组,让左树根结点指向右树根结点即可。不过在此之前,我们需要调用两次 $Find$ 函数以寻找 $5$ 和 $1$ 的父亲结点。```cpp line-numbers lines=4-5void Union(int x,int y){ //假设要合并x和y所在的集合int rootx=Find(x); //找x的父亲结点int rooty=Find(y); //找y的父亲结点if(rootx!=rooty) //两树的父亲结点不一样->不是同一棵树上的结点parent[rootx]=rooty; //左树指向右树}```现在,我们就将左树成功合并到了右树上。但是合并后的树层数太多,所以我们需要对我们的 $Union$ 函数进行优化。138 行未改动全部展开parent[rootx]=rooty;}else{//两树等高parent[rooty]=rootx; //或parent[rootx]=rooty;parent[rootx]--; //因为是负数,-1就是绝对值+1//或parent[rooty]--;}}void Union_size(int x,int y){ //按结点数合并示例,实际写的时候改为void Union(int x,int y);int rootx=Find(x);6 行未改动parent[rootx]=rooty;}else{//两树结点数相等parent[rooty]=rootx; //或parent[rootx]=rooty;parent[rootx]-=parent[rooty]; //因为是负数,减去被合并树的高度就是绝对值加上被合并树的高度//或parent[rooty]-=parent[rootx];}}```11 行未改动