如何清空左偏树
  • 板块学术版
  • 楼主wangziwenhk
  • 当前回复9
  • 已保存回复11
  • 发布时间2024/6/6 15:53
  • 上次更新2024/6/6 19:19:58
查看原帖
如何清空左偏树
727556
wangziwenhk楼主2024/6/6 15:53

struct Node {
    int dist, value;
    Node *left = nullptr, *right = nullptr;
};

Node *meld(Node *x, Node *y) {
    if (x == nullptr)return y;
    if (y == nullptr)return x;
    if (x->value < y->value)swap(x, y);
    x->right = meld(x->right, y);
    if (!x->left || x->right->dist > x->left->dist) {
        swap(x->left, x->right);
    }
    if (x->right == nullptr)x->dist = 1;
    else x->dist = x->right->dist + 1;
    return x;
}

Node *insert(Node *x, int value) {
    Node *temp = new Node;
    temp->dist = 1;
    temp->value = value;
    return meld(x, temp);
}

Node *pop(Node *x) {
    Node *left = x->left;
    Node *right = x->right;
    delete x;
    return meld(left, right);
}

unordered_map<int, int> father;
unordered_map<int, Node *> node;

int find_root(int x) {
    if (father[x] == x)return x;
    return father[x] = find_root(father[x]);
}

void add(int x, int y) {
    int tx= find_root(x);
    int ty = find_root(y);
    if(tx==ty)return;
    father[x] = y;
    node[y] = meld(node[x], node[y]);
}
2024/6/6 15:53
加载中...