码迷,mamicode.com
首页 > 其他好文 > 详细

【模板】左偏树

时间:2018-12-03 13:53:21      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:find   ++   turn   cstring   ios   pre   continue   bsp   class   

如题,这是一个模板。。。

 1 #include <algorithm>
 2 #include <iostream>
 3 #include <cstring>
 4 #include <cstdio>
 5 #include <cctype>
 6 
 7 inline void read(int & x)
 8 {
 9     x = 0;
10     int k = 1;
11     char c = getchar();
12     while (!isdigit(c))
13         if (c == -) c = getchar(), k = -1;
14         else c = getchar();
15     while (isdigit(c))
16         x = (x << 1) + (x << 3) + (c ^ 48),
17         c = getchar();
18     x *= k;
19 }
20 
21 const int MAXN = 100010;
22 int n, m, opt, x, y, tot = 0;
23 int faz[MAXN], son[MAXN][2], val[MAXN], dis[MAXN];
24 
25 inline int Find(int u)
26 {
27     while (faz[u]) u = faz[u];
28     return u;
29 }
30 
31 int Merge(int a, int b)
32 {
33     if (!a || !b) { return a + b; }
34     if (val[a] > val[b] || (val[a] == val[b] && a > b))
35         std::swap(a, b);
36     son[a][1] = Merge(son[a][1], b);
37     faz[son[a][1]] = a;
38     if (dis[son[a][0]] < dis[son[a][1]]) 
39         std::swap(son[a][1], son[a][0]); 
40     dis[a] = dis[son[a][1]] + 1;
41     return a;
42 }
43 
44 int qa, qb, cc;
45 
46 inline void Merge_opt(int aa, int bb)
47 {
48     if (val[aa] == -1 || val[bb] == -1) return;
49     qa = Find(aa), qb = Find(bb);
50     if (qa == qb) return;
51     Merge(qa, qb);
52 }
53 
54 signed main()
55 {
56     read(n), read(m);
57     for (int i = 1; i <= n; ++i)
58         read(val[i]);
59     for (int i = 1; i <= m; ++i)
60     {
61         read(opt), read(x);
62         if (opt == 1) read(y), Merge_opt(x, y);
63         else
64         {
65             if (val[x] == -1) {puts("-1"); continue;}
66             y = Find(x);
67             printf("%d\n", val[y]);
68             faz[son[y][0]] = faz[son[y][1]] = 0;
69             val[y] = -1;
70             Merge_opt(son[y][0], son[y][1]);
71         }
72     }
73     return 0;
74 }

 

【模板】左偏树

标签:find   ++   turn   cstring   ios   pre   continue   bsp   class   

原文地址:https://www.cnblogs.com/yanyiming10243247/p/10057795.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!