手写最小堆

最小堆板子

#include <cstdio>
#include <cstring>
#include <cstdint>
#include <iostream>

using namespace std;
typedef long long ll;
const ll inf = 1ll<<32;
const int maxn = 4e6+10;

struct node {
    ll val; char str[9];
    inline void read() {
        scanf("%lld %s", &val, str);
    }
    inline bool operator>(const node &p) {
        return val<p.val || (val==p.val && strcmp(str, p.str)<0);
    }
}a[maxn], now;
int n, m, pn;

void fixdown(int x) {
    int f=x, k;
    while((k=f*2)<=pn) {
        if(k<pn && a[k+1] > a[k]) ++k;
        if(a[f]>a[k]) break;
        node tmp = a[f]; a[f] = a[k]; a[k] = tmp;
        f = k;
    }
}

void fixup() {
    int k=pn, f;
    while((f = (k>>1))>=1) {
        if(a[f] > a[k]) break;
        node tmp = a[k];
        a[k] = a[f];
        a[f] = tmp;
        k = f;
    }
}

void pop() {
    a[1] = a[pn--];
    fixdown(1);
}

void push(node &x) {
    a[++pn] = x;
    fixup();
}

int main() {
    scanf("%d%d", &n, &m);
    for (int i=1; i<=n; ++i) {
        now.read();
        push(now);
    }
    for (int i=1; i<=m && pn>=1; ++i) {
        puts(a[1].str);
        a[1].val <<= 1;
        if(a[1].val >= inf)
            pop();
        fixdown(1);
    }
    return 0;
}
上一篇:模拟电子技术-02


下一篇:LeetCode Algorithm 0060 - Permutation Sequence (Medium)