美文网首页
优先队列

优先队列

作者: 不知名小号 | 来源:发表于2020-09-02 21:19 被阅读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();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:优先队列

          本文链接:https://www.haomeiwen.com/subject/othgsktx.html