poj1988-種類並查集

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   資料   for   

題意:有N個立方體(1<=N <=30,000),相應地初始時每個立方體放在一個棧中,有兩種操作:1、M X Y:把包含第X個立方體的棧中的所有立方體當做一個整體拿出來壓入包含第Y個立方體的棧中(即是放在Y棧中的棧頂);2、C X:詢問編號為X的立方體下有幾個立方體。

思路:把每次1操作後的棧底元素當做根節點。記錄棧中元素到根節點的距離h[],記錄棧中元素的子節點個數ch[]。Find()路徑壓縮的時候更新的當前節點到根節點的距離h[]即是h[]加上其原父節點到根節點的距離。合并兩個棧元素的時候直接合并兩根節點,設根節點為X 和 Y,Y 為新的根節點, X與Y的距離h[X]為X還沒放入棧中棧裡的元素個數,即

h[x] = ch[Y],ch[Y] += ch[x]。

總結:開始自己想的是只記錄更新除父節點數組之外的一個節點資訊,然後棧頂元素當父節點,結果掉進了死胡同,後來考慮到棧中元素到棧底的距離才把思路掰回來了。有時候想不明白還是要多想想資料多畫畫圖。

AC代碼:

 1 #include <cstdio> 2 #include <iostream> 3 #include <vector> 4 const int maxn = 30004; 5 int par[maxn], h[maxn], ch[maxn]; 6 void init() 7 { 8     for(int i = 0; i < maxn; i++) { 9         par[i] = i;10         h[i] = 0;11         ch[i] = 1;12     }13 }14 int Find(int x)15 {16     if(x == par[x]) return x;17     int t = par[x];18     par[x] = Find(par[x]);19     h[x] += h[t];20     return par[x];21 }22 void Union(int a, int b)23 {24     int x = Find(a);25     int y = Find(b);26     if(x != y) {27         par[x] = y;28         h[x] = ch[y];29         ch[y] += ch[x];30     }31 }32 33 int main()34 {35     int p;36     while(scanf("%d", &p) != EOF) {37         init();38         while(p--) {39             char s[2];40             scanf("%s", s);41             if(s[0] == ‘M‘) {42                 int a, b;43                 scanf("%d%d", &a, &b);44                 Union(a, b);45             }46             else {47                 int a; scanf("%d", &a);48                 Find(a);49                 printf("%d\n", h[a]);50             }51         }52     }53     return 0;54 }
View Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.