杂篇之2-堆篇

来源:互联网 发布:淘宝的安逸猿 编辑:程序博客网 时间:2024/06/05 20:09

1.基本操作

  • H.top() :返回堆顶元素,但是不删除该元素
  • H.pop() :删除堆顶元素
  • H.push(item) :往堆顶插入元素item

2.基于库的int类型的最大堆,最小堆

下面对堆的构建都是基于标准库中的priority_queue

  • priority_queue默认情况下建立在vector之上

2.1 最大堆

默认情况下,基于int类型构建的最大堆为最大堆

    //priority_queue<int,vector<int>,less<int> > maxHead; //显示构建最大堆    priority_queue<int> maxHead; // 默认是最大堆     for(int i=0;i<10;++i){        maxHead.push(i);    }    cout<<maxHead.top()<<endl;    maxHead.pop();    cout<<maxHead.top()<<endl;

2.2 最小堆

    priority_queue<int,vector<int>,greater<int> > minHead; //构建最小堆    for(int i=9;0<i;--i){        minHead.push(i);    }    cout<<minHead.top()<<endl;    minHead.pop();    cout<<minHead.top()<<endl;

3.基于结构体构建堆

这里面包含两种类型构建最大堆

3.1 方式1-最大堆

struct node{    int key; // 根据key进行大小的比较     int value;    node(int _key=0,int _value=0):key(_key),value(_value){    }}; struct cmp{    bool operator()(const node &x1,const node&x2){        return x1.value<x2.value;    }};

而后构建

    priority_queue<node,vector<node>,cmp> maxH2;     int num[]={3,4,1,2,5,7};    for(int i=0;i<6;++i)    {        node x1(i,num[i]);        maxH2.push(x1);    }    node x2=maxH2.top();    cout<<x2.key<< " "<<x2.value<<endl;    maxH2.pop();    x2=maxH2.top();    cout<<x2.key<< " "<<x2.value<<endl;

3.2 方式2-构建最小堆

重载小于号,但是记着重载如果在类element中,则重载必须是友元形式,否则会出错

struct element{    int key; // 根据x进行大小的比较     int value;    element(int _key=0,int _value=0):key(_key),value(_value){    }    friend  bool operator<(const element &x1,const element &x2); // 这一句话不要也可以}; bool operator<(const element &x1,const element &x2){        return x1.key<x2.key;}

构建过程如下:

    priority_queue<element,vector<element> > maxH3; // 重载小于号  在类外实现,不能在类内实现     for(int i=0;i<6;++i)    {        element x1(i,num[i]);        maxH3.push(x1);    }    element x3=maxH3.top();    cout<<x3.key<< " "<<x3.value<<endl;    maxH3.pop();    x3=maxH3.top();    cout<<x3.key<< " "<<x3.value<<endl;
原创粉丝点击