Monkey King【大根堆】

这篇博客探讨了一群猴子打架后成为朋友的问题,通过维护大根堆或二叉树平衡来求解战斗力最大的猴子。算法采用启发式合并操作,每次合并时保持二叉树深度平衡,确保复杂度优化。文章详细解释了如何在合并和删除过程中更新节点,并给出了C++实现的代码示例。
摘要由CSDN通过智能技术生成

题目链接


  有N只孤独的猴子,然后他们会打M次架,每次打架的两只猴子战斗力减半,并且会成为朋友,朋友的朋友也是朋友,问的是朋友中战力最大的猴子是有多少战力?

  于是,考虑维护这样的一个大根堆,每次将小的大根堆推给大的,相当于是启发式合并的操作,复杂度O(Nlog(N)log(N))

  或者,我们可以直接进行维护,我们维护一个二叉树的“深度”,然后尽量保证深度平衡,也就是使得整棵二叉树的深度尽可能小,所以,我们定义一个dist,表示它和它的子树中的dist最小的值+1,但是这样的维护最后可能退化会形成一条链,不妥,不如我们让左子树的dist大于右子树的dist,然后这样子推下去,最后让根节点的dist等于右子树的dist+1即可。

  于是,每次就是合并两棵子树就可以了,合并的时候复杂度为O(log(N))级别,然后删除的时候,实际上就是对左右两棵子树合并,然后插入的时候实际上就是对一个堆大小为1的点的合并了。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <bitset>
#include <unordered_map>
#include <unordered_set>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
#define pii pair<int, int>
#define MP(a, b) make_pair(a, b)
using namespace std;
typedef unsigned long long ull;
typedef unsigned int uit;
typedef long long ll;
const int maxN = 1e5 + 7;
int N, M;
struct node
{
    int val, d, c[2], fa;
    node(int a=0, int b=0, int c1=0, int c2=0, int f=0):val(a), d(b), c{c1, c2}, fa(f) {}
} t[maxN];
int fid(int x) { return x == t[x].fa ? x : t[x].fa = fid(t[x].fa); }
int Merge(int x, int y)
{
    if(!x || !y) return x | y;
    if(t[x].val < t[y].val) swap(x, y);
    t[x].c[1] = Merge(t[x].c[1], y);
    t[t[x].c[1]].fa = x;
    if(t[t[x].c[0]].d < t[t[x].c[1]].d) swap(t[x].c[0], t[x].c[1]);
    t[x].d = t[t[x].c[1]].d + 1;
    return x;
}
int pop(int x)
{
    t[t[x].c[0]].fa = t[x].c[0];
    t[t[x].c[1]].fa = t[x].c[1];
    t[x].val >>= 1;
    int y = Merge(t[x].c[0], t[x].c[1]);
    memset(t[x].c, 0, sizeof(t[x].c));
    return Merge(x, y);
}
int main()
{
    while(scanf("%d", &N) != EOF)
    {
        for(int i=1; i<=N; i++)
        {
            scanf("%d", &t[i].val);
            memset(t[i].c, 0, sizeof(t[i].c));
            t[i].fa = i; t[i].d = 0;
        }
        scanf("%d", &M);
        for(int i=1, x, y, fx, fy, ff; i<=M; i++)
        {
            scanf("%d%d", &x, &y);
            fx = fid(x); fy = fid(y);
            if(fx == fy) { puts("-1"); continue; }
            if(t[fx].val < t[fy].val) swap(fx, fy);
            ff = Merge(pop(fx), pop(fy));
            printf("%d\n", t[ff].val);
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wuliwuliii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值