【每日刷题】Day100

时间:2025-03-15 08:40:59

//C++堆(大堆)的实现。

#include <iostream>

#include <vector>

using namespace std;

class Heap

{

public:

    Heap()

        :_size(0)

    {}

    void Swap(int& x,int& y)

    {

        int tmp = x;

        x = y;

        y = tmp;

    }


//向下调整

    void AdjustDown(int parents)

    {

        int child = parents*2+1;

        while(child<_size)

        {

            if(child+1<_size&&_arr[child+1]>_arr[child])

                child++;

            if(_arr[child]>_arr[parents])

                Swap(_arr[child],_arr[parents]);

            else

                break;

            parents = child;

            child = parents*2+1;

        }

    }

//向上调整

    void Adjustup(int child)

    {

        int parents = (child-1)/2;

        while(child>0)

        {

            if(_arr[child]>_arr[parents])

                Swap(_arr[child],_arr[parents]);

            else

                break;

            child = parents;

            parents = (child-1)/2;

        }

    }

//入堆

    void push(int val)

    {

        _arr.push_back(val);

        Adjustup(_size);

        _size++;

    }

//删除堆顶元素

    void pop()

    {

        if(_size==0)

            cout<<"empty"<<endl;

        else

        {

            cout<<_arr[0]<<endl;

            Swap(_arr[0],_arr[_size-1]);

            _arr.pop_back();

            _size--;

            AdjustDown(0);

        }

    }

//获取堆顶元素

    void top()

    {

        if(_size==0)

            cout<<"empty"<<endl;

        else

            cout<<_arr[0]<<endl;

    }


 

private:

    vector<int> _arr;

    size_t _size;

};

int main()

{

    Heap h;

    int n = 0;

    cin>>n;

    while(n--)

    {

        int data = 0;

        string s;

        cin>>s;

        if(s=="push")

        {

            cin>>data;

            (data);

        }

        if(s=="top")

            ();

        if(s=="pop")

            ();

    }

    return 0;

}