int superior[MAXN]; int find_root(int son) { // int temp=son; // while(son!=superior[son]) // son=superior [son]; // superior[temp]=son;//路径压缩 // return son; if(son==superior[son]) { return son; }else { superior[son]=find_root(superior[son]);//路径压缩 return superior[son]; } } void union_fa(int x1,int x2) { int x1_superior=find_root(x1); int x2_superior=find_root(x2); if(x1_superior!=x2_superior) superior[x2_superior]=x1_superior; }
//初始化
for(int i=0;i<=n;i++) superior[i]=i;
测试代码
superior[1]=2;
superior[2]=4;
superior[4]=0;
superior[5]=1;
superior[3]=5;
superior[0]=100;
cout<<find_root(3);
结果:100
原文链接: https://www.cnblogs.com/lxzbky/p/12496944.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/400055
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!