ZOJ 2334 Monkey King(左偏树)

74 篇文章 0 订阅
3 篇文章 0 订阅

题目链接:点击打开链接

思路:左偏树模板题, 需要维护集合关系, 这个可以用并查集很方便的维护, 另外需要用一个数组来维护每个点所在的左偏树编号。

细节参见代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std;
typedef long long ll;
typedef long double ld;
const ld eps = 1e-9, PI = 3.1415926535897932384626433832795;
const int mod = 1000000000 + 7;
const int INF = 0x3f3f3f3f;
// & 0x7FFFFFFF
const int seed = 131;
const ll INF64 = ll(1e18);
const int maxn = 3e5 + 10;
int T,n,m;
int tot, u, a, b, v[maxn], l[maxn], r[maxn], d[maxn], p[maxn], id[maxn];
int _find(int x) { return p[x] == x ? x : p[x] = _find(p[x]); }
int Merge(int x, int y) {
    if(!x) return y;
    if(!y) return x;
    if(v[x] < v[y]) swap(x, y);
    r[x] = Merge(r[x], y);
    if(d[l[x]] < d[r[x]]) swap(l[x], r[x]);
    d[x] = d[r[x]] + 1;
    return x;
}
int init(int x) {
    tot++;
    v[tot] = x;
    l[tot] = r[tot] = d[tot] = 0;
    return tot;
}
int Insert(int x, int y) {
    return Merge(x, init(y));
}
int top(int x) {
    return v[x];
}
int pop(int x) {
    return Merge(l[x], r[x]);
}
int main() {
    while(~scanf("%d",&n)) {
        tot = 0;
        for(int i = 1; i <= n; i++) {
            p[i] = i;
            id[i] = i;
        }
        for(int i = 1; i <= n; i++) {
            scanf("%d",&u);
            init(u);
        }
        scanf("%d",&m);
        while(m--) {
            scanf("%d%d",&a,&b);
            int x = _find(a), y = _find(b);
            if(x == y) printf("-1\n");
            else {
                int u = top(id[x]);
                id[x] = pop(id[x]);
                id[x] = Insert(id[x], u/2);
                u = top(id[y]);
                id[y] = pop(id[y]);
                id[y] = Insert(id[y], u/2);
                p[x] = y;
                id[y] = Merge(id[x], id[y]);
                u = top(id[y]);
                printf("%d\n",u);
            }
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值