代码拉取完成,页面将自动刷新
#pragma once
#include <iostream>
#include <queue>
#include "stack.h"
#include "queue.h"
using namespace std;
namespace fast
{
//template<class T, class Container=vector<T>>
//class priority_queue
//{
//public:
// void swap(T& x, T& y)
// {
// T tmp = x;
// x = y;
// y = tmp;
// }
// void adjust_up(int child)//新插入的数据下标为child
// {
// int parent = (child - 1) / 2;
// while (child > 0)
// {
// if (_con[child] < _con[parent])
// {
// swap(_con[child], _con[parent]);
// child = parent;
// parent = (child - 1) / 2;
// }
// else
// {
// break;
// }
// }
// }
// void adjust_down(int parent)
// //n表示数据个数(size()),parent默认为0
// {
// int child = parent * 2 + 1;
// while (child < size())
// {
// if (child + 1 < size() && _con[child + 1] < _con[child])
// {
// child++;
// }
// if (_con[child] < _con[parent])
// {
// swap(_con[child], _con[parent]);
// parent = child;
// child = parent * 2 + 1;
// }
// else
// {
// break;
// }
// }
// }
// void push(const T& x)
// {
// _con.push_back(x);
// adjust_up(_con.size()-1);
// }
// void pop()
// {
// swap(_con[0], _con[_con.size() - 1]);
// _con.pop_back();
// adjust_down(0);
// }
// const T& top()
// {
// return _con[0];
// }
// size_t size()
// {
// return _con.size();
// }
// bool empty()
// {
// return _con.empty();
// }
//private:
// Container _con;
//};
template<class T>
class less
{
public:
bool operator()(const T&x, const T& y)
{
return x < y;
}
};
template<class T>
class greater
{
public:
bool operator()(const T& x, const T& y)
{
return x > y;
}
};
template<class T, class Container=vector<T>, class Compare=less<int>>
class priority_queue
{
public:
void adjust_up(int child)
{
int parent = (child - 1) / 2;
while (child>0)
{
if (_com(_con[child] , _con[parent]))
{
std::swap(_con[child], _con[parent]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void adjust_down(int parent)
{
int child = parent * 2 + 1;
while (child < _con.size())
{
if (child + 1 < _con.size() && _com(_con[child + 1] ,_con[child]))
{
++child;
}
if (_com(_con[child], _con[parent]))
{
swap(_con[child], _con[parent]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void push(const T& x)
{
_con.push_back(x);
adjust_up(_con.size() - 1);
}
void pop()
{
swap(_con[0], _con[_con.size() - 1]);
_con.pop_back();
adjust_down(0);
}
const T& top()
{
return _con[0];
}
size_t size()
{
return _con.size();
}
bool empty()
{
return _con.empty();
}
private:
Container _con;
Compare _com;
};
void test_priority_queue()
{
priority_queue<int, vector<int>, greater<int>> pq;
pq.push(4);
pq.push(7);
pq.push(2);
pq.push(9);
pq.push(3);
while (!pq.empty())
{
cout << pq.top() << " ";
pq.pop();
}
cout << endl;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。