並查集--連通圖相關
阿新 • • 發佈:2017-06-10
做的 turn ret color 非遞歸 路徑 行數 再看 一次
早上一番搗鼓,把以前丟失的onenote筆記找出來一部分.
看到並查集,大二做的筆記,現在已經毫無印象了
記得當時看的時候挺費勁,雲裏霧裏的
現在再看一遍竟然毫無壓力,一次讀懂
其實確實挺簡單的,沒有那麽高深.可能當時玩acm的時候太沒自信了,看啥都難...
核心思想是用一個節點代表一塊連通分支
可以通過路徑壓縮來減少以後查找的時間
非路徑壓縮遞歸寫法:
int fFind(int i) { if(pre[i]!=i) pre[i]=fFind(pre[i]); return pre[i]; }
路徑壓縮非遞歸寫法:
int fFind(int i) {int roooot=i; while(pre[roooot]!=roooot) roooot=pre[roooot];//尋根 int tmp; while(pre[i]!=roooot) { tmp=pre[i]; pre[i]=roooot; i=tmp; }//路徑壓縮 return pre[i]; }
適用於代碼行數強迫癥的一行寫法:
int find(int x) { return p[x]==x?x:p[x]=find(p[x]); }
兩個相關並查集交融的mix函數:
mix函數 void mix(int a,int b) { int i=fFind(a),j=fFind(b); if(i!=j) pre[i]=j; }
並查集--連通圖相關