poj-1988 Cube Stacking **

來源:互聯網
上載者:User
 1 /*
2 * poj-1988 Cube Stacking.cpp
3 *
4 * Created on: 2012-2-12
5 * Author: LongDou
6 *
7 * 並查集:
8 * 每個節點有3個域:1、fa[x]:並查集中x的父節點 (fa[x]必壓在x之下,但不一定直接相鄰)
9 * 2、rank[x]:在x之下(不包括x)且在fa[x]之上(包括fa[x])的方塊數
10 * (如果直接記錄x之下的總方塊數,則每次合并都需更新某個集合中所有元素的
11 * rank域;而這樣記錄的話,合併作業只需更新某個集合的根結點的rank域,
12 * 同時對一次詢問“C x”,只需計算x到根的rank值之和,複雜度不大)
13 * 3、stackNum[x]:x當前所在的stack標號(僅樹根節點有意義)
14 *
15 * 每次 M x y 操作, 合并x和y兩個集合,注意更新各stack當前所含的方塊數
16 * findSet操作在路徑壓縮時注意更新rank域
17 *    
        (另:劉汝佳的黑書中P81例題3與此題類似,解題也一樣,只是略簡潔一些。。。)
18 */
19 #include <cstdio>
20 using namespace std;
21
22 const int maxn = 30000 + 10;
23 const int maxp = 100000 + 10;
24
25 int num[maxn] = {}; //stack當前所含的方塊數
26 int fa[maxn], rank[maxn], stackNum[maxn];
27
28 void init(){
29 for(int i=0; i<maxn; i++){
30 num[i] = 1;
31 fa[i] = i;
32 rank[i] = 0;
33 stackNum[i] = i;
34 }
35 }
36
37 int findSet(int x){
38 if(x == fa[x])
39 return x;
40
41 int tmp = fa[x];
42 fa[x] = findSet(fa[x]);
43 rank[x] += rank[tmp]; //更新rank域
44
45 return fa[x];
46 }
47
48 void unionSet(int x, int y){
49 int fx = findSet(x);
50 int fy = findSet(y);
51
52 if(fx == fy) return;
53
54 fa[fx] = fy;
55 rank[fx] += num[stackNum[fy]];
56
57 //更新各stack當前所含的方塊數
58 num[stackNum[fy]] += num[stackNum[fx]];
59 num[stackNum[fx]] = 0;
60 }
61
62 int main(){
63 int p, x, y;
64 char op;
65
66 init();
67
68 scanf("%d", &p);
69 for(int i=0; i<p; i++){
70 getchar();
71 scanf("%c", &op);
72
73 if(op == 'M'){
74 scanf("%d%d", &x, &y);
75 unionSet(x, y);
76 }
77 else{
78 scanf("%d", &x);
79 int fx = findSet(x);
80 printf("%d\n", rank[x] + rank[fx]);
81 }
82 }
83
84
85
86 return 0;
87 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.