我正在上一門算法課程,其中討論了加權快速聯合查找。我很困惑為什么我們關心樹的大小而不是深度?當我嘗試編寫代碼時,我的代碼看起來與提供的解決方案不同。根據我的理解,當涉及到并集函數(lg n)的運行時間時,樹的大?。渲泄濣c的總數)并不像樹的深度那么重要,因為它是深度確定需要多少次查找才能到達節點的根?謝謝My code:public void union(int p, int q) { int root_p = root(p); int root_q = root(q); // If the two trees are not already connected, union them if(root_p != root_q) { // The two trees aren't connected, check which is deeper // Attach the one that is more shallow to the deeper one if (depth[root_p] > depth[root_q]) { // p is deeper, point q's root to p id[root_q] = root_p; } else if (depth[root_q] > depth[root_p]) { // q is deeper, point p's root to p id[root_p] = root_q; } else { // They are of equal depth, point q's root to p and increment p's depth by 1 id[root_q] = root_p; depth[root_p] += 1; } }}Solution code provided:public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make smaller root point to larger one if (size[rootP] < size[rootQ]) { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } else { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } count--;}
1 回答

四季花海
TA貢獻1811條經驗 獲得超5個贊
您是正確的,深度(實際上是高度)與運行時間更直接相關,但使用任一深度都會導致聯合和查找的運行時間為O(log N) 。
證明很簡單——假設當我們開始時(當所有集合都不相交時),每個高度為h的根至少有2 (h-1)個節點,這個不變量由并集和查找操作來維護。因此,如果一個節點的大小為n,那么它的高度最多為Floor(log 2 (n))+1
所以任何一個都可以。但是,很快您就會了解路徑壓縮,這使得跟蹤根的高度變得困難,但大小仍然可用。那時,您將能夠使用“rank”(類似于“height”),或者繼續使用“size”。同樣,任何一個都可以,但我發現尺寸更容易推理,所以我總是使用它。
添加回答
舉報
0/150
提交
取消