繁体   English   中英

维护std :: priority_queue的堆属性

[英]Maintaining heap property of std::priority_queue

我期待基于边权重创建最大堆。 但是,在打印堆时,很明显它没有维护其二进制堆属性。 我该如何处理?

#include <iostream>
#include <cstring>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <bitset>
#include <climits>
#include <ctime>
#include <algorithm>
#include <functional>
#include <stack>
#include <queue>
#include <list>
#include <deque>
#include <sys/time.h>
#include <iomanip>
#include <cstdarg>
#include <utility> //std::pair
#include <cassert>
using namespace std;


typedef struct{
        int u, v, weight;
    }edge;


class comparator{
public:
    bool operator()(const edge &e1, const edge &e2)
        {
            if(e1.weight<e2.weight)
                return true;
        }
};


void print_queue(priority_queue<edge, vector<edge> ,comparator> q)
{
    while(!q.empty())
        cout<<q.top().weight<<" ", q.pop();
    cout<<endl<<endl;
}

int main()
{

    priority_queue<edge, vector<edge> , comparator> q;
    edge e1={1,2,10};
    edge e2={1,3,23};
    edge e3={1,4,4};
    edge e4={1,5,99};
    edge e5={1,6,43};
    edge e6={1,7,29};

    q.push(e1);
    q.push(e2);
    q.push(e3);
    print_queue(q);
    q.push(e4);
    q.push(e5);
    q.push(e6);
    print_queue(q);
}

该错误在您的比较器功能中。 我在e1.weight> = e2.weight的情况下添加了“return false”:

    bool operator()(const edge &e1, const edge &e2)
    {
        if(e1.weight<e2.weight)
            return true;
        return false;
    }

我认为现在它的工作方式与您期望它的工作方式相同:

之前:

[jsaxton @ jsaxton-dev~] $ ./a.out 4 23 10

29 23 4 10 43 99

后:

[jsaxton @ jsaxton-dev~] $ ./a.out 23 10 4

99 43 29 23 10 4

if(e1.weight<e2.weight)
       return true;

好吧,其他部分呢?

工作得很好

else return false;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM