日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

并查集(Disjiont Set)

發布時間:2025/3/8 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 并查集(Disjiont Set) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

并查集

并查集的最大作用是檢測一個圖上面存不存在環。

無向圖,六個頂點
顯然 1-2-4-3連成一個環

#include<stdio.h> #include<stdlib.h>#define VERTICES 6void initialise(int parent[]){int i;for(i=0;i<VERTICES;i++){parent[i]=-1; }}int find_root(int x,int parent[]){int x_root=x;while(parent[x_root]!=-1){x_root=parent[x_root];}return x_root; } /*1- union successfully ,0-failed*/ int union_vertices(int x,int y,int parent[]){int x_root=find_root(x,parent);int y_root=find_root(y,parent);if(x_root==y_root){return 0;} else{parent[x_root]=y_root;return 1;}}int main(){int parent[VERTICES]={0};int edges[6][2]={{0,1},{1,2},{1,3},{2,4},{3,4},{2,5}};initialise(parent);int i;for(i=0;i<6;i++){int x=edges[i][0];int y=edges[i][1];if(union_vertices(x,y,parent)){printf("Cycle detected!\n");exit(0);}} printf("no cycle found.\n");return 0; }

進行優化后:

#include<stdio.h> #include<stdlib.h>#define VERTICES 6void initialise(int parent[],int rank[]) {int i;for(i=0; i<VERTICES; i++) {parent[i]=-1;rank[i]=0;}}int find_root(int x,int parent[]) {int x_root=x;while(parent[x_root]!=-1) {x_root=parent[x_root];}return x_root; }/*1- union successfully ,0-failed*/ int union_vertices(int x,int y,int parent[],int rank[]) {int x_root=find_root(x,parent);int y_root=find_root(y,parent);if(x_root==y_root) {return 0;} else { // parent[x_root]=y_root;if(rank[x_root]>rank[y_root]) {parent[y_root]=x_root;} else if(rank[y_root]>rank[x_root]) {parent[x_root]=y_root;} else {parent[x_root]=y_root;rank[y_root]++;}return 1;}}int main(void) {int parent[VERTICES]= {0};int rank[VERTICES]= {0};int edges[6][2]= {{0,1},{1,2},{1,3},{2,4},{3,4},{2,5}};initialise(parent,rank);for(int i=0; i<6; i++) {int x=edges[i][0];int y=edges[i][1];if((union_vertices(x,y,parent,rank)==0)) {printf("Cycle detected!\n");exit(0);}}printf("no cycle found.\n");return 0; }

總結

以上是生活随笔為你收集整理的并查集(Disjiont Set)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。