优先队列

2020-09-02  本文已影响0人  不知名小号
#include <iostream>
#include <vector>
using namespace std;

template<typename T>
class Priori_queue {
    vector<T> v;
public:
    Priori_queue(){}
    void push(T a) {
        v.push_back(a);
        int target = a;
        int index = v.size() - 1;
        int p = (index - 1) / 2;
        while (v[index] > v[p]) {
            swap(v[index], v[p]);
            index = p;
            p = (index - 1) / 2;
        }
    }
    T top() {
        cout << v.size() << endl;
        return v[0];
    }
    void pop() {
        if (v.size() == 0) {
            return;
        }
        swap(v[0], v[v.size() - 1]);
    //  printf("pop v[0] %d", v[0]);
    //  printf("v.size() %d", v.size());
        v.pop_back();
    //  printf("v.size() %d", v.size());
        int i = 0;
        while (i * 2 + 1 < v.size()) {
            int l = i * 2 + 1;
            int r = i * 2 + 2;
            if (r < v.size() && v[r] > v[l]) {
                l = r;
            }
            if (v[i] >= v[l]) {
                break;
            }
            swap(v[i], v[l]);
            i = l;
        }
    }
};
int main() {
    Priori_queue<int> p;
    while (1) {
        int cmd;
        cin >> cmd;
        if (cmd == 1) {
            cout << "push";
            int x;
            cin >> x;
            p.push(x);
        }
        else if (cmd == 2) {
            cout << "top";
            cout << p.top() << endl;;
        }
        else if (cmd == 3) {
            cout << "pop" << endl;
            p.pop();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读