數據結構(集合與運算——並查集)代碼實現

/* 並查集*/
typedef struct 4{
    elementtype data;
    int parent;
}settype;

/*查找某個元素所在的集合(用根節點表示)*/
int find (settype s[],elementtype x)
{//在數組S中查找值爲X的元素所屬的集合 
 // maxsize是全局變量,爲數組S的最大長度 
    int i;
    for(i=0;i<maxsize&&s[i].data!=x;i++);
    if(i>=maxsize) return -1;//未找到X,返回-1 
    for(;s[i].parent>=0;i=s[i].parent);
    return i;//找到X所屬集合,返回樹根節點在數組S中的下標 
 } 
 
 /*集合的並運算*/
 /*分別找道X1和X2兩個元素所在集合樹的根節點
 如果它們不同根,則將其中一個根節點的父節點指針設置成
 另一個根節點的數組下標*/
 void union(settype s[],elementtype x1,elementtype x2) 
 {
     int root1,root2;
     root1=find(s.x1);
     root2=find(s,x2);
     if(root1!=root2)
     {
         s[root2].parent=root1;
    }
 }
  
  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章