题解 | #【模板】堆#

【模板】堆

https://www.nowcoder.com/practice/13f61c8c92404f5ea5d6fa4c692869fb

#include<bits/stdc++.h>
#include <vector>
using namespace std;
void down(int r, vector<int>& h, int size) {
    //h->heap;r->root;l->larger_one;
    int l = r;
    if (r * 2 <= size && h[r * 2] > h[l]) l = r * 2;
    if (r * 2 + 1 <= size && h[r * 2 + 1] > h[l]) l = r * 2 + 1;
    if (r != l) {
        swap(h[r], h[l]);
        down(l, h, size);
    }
    return;
}
void up(int c, vector<int>& h) {
    //h->heap;c->child;l->larger_one;
    int l = c;
    if (c % 2 == 0 && h[c / 2] < h[l]) l = c / 2;
    else if (c % 2 == 1 && h[(c - 1) / 2] < h[l]) l = (c - 1) / 2;
    if (c != l) {
        swap(h[c], h[l]);
        if (l > 1) up(l, h);
    }
    return;
}
int main() {
    int n = 0, size = 0, x = 0;
    string s;
    cin >> n;
    vector<int> heap(n + 1, 0);
    while (n--) {
        cin >> s;
        if (s == "push") {
            cin >> x;
            heap[++size] = x;
            if (size != 1) up(size, heap);
        } else if (s == "top") {
            if (heap[1]) {
                cout << heap[1] << endl;
            } else {
                cout << "empty" << endl;
            }
        } else {
            if (heap[1]) {
                cout << heap[1] << endl;
                swap(heap[1], heap[size]);
                heap[size--] = 0;
                down(1, heap, size);
            } else {
                cout << "empty" << endl;
            }
        }
    }
}

全部评论

相关推荐

03-31 17:40
已编辑
门头沟学院 算法工程师
程序员牛肉:小牛肉来也! 也不要焦虑啦,你第一志愿还没有结束,只是回到人才库(泡大池子等待各个部门挑选)而已。仅仅代表你不符合这个组的用人标准,并不能够说明你在本次暑期实习中没机会加入美团了。 还是平复好心态,不断的复盘,等待下一次面试就好了。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务