今天考试罚坐的时候百无聊赖突发奇想是不是可以写个多叉堆,于是就实现了一下:
#include<bits/stdc++.h>
using namespace std;
namespace jqQt0220
{
template<typename T,typename Cmp=std::less<T>,std::size_t Base=2>
class heap
{
private:
std::vector<T> _val;
std::size_t _fa(std::size_t _p)
{
return (_p-1)/Base;
}
std::size_t _son(std::size_t _p,std::size_t _i)
{
return _p*Base+_i;
}
Cmp _cmp;
public:
T top()
{
return _val.front();
}
void push(T _x)
{
_val.push_back(_x);
std::size_t nw=_val.size();
while(nw!=0)
{
std::size_t nx=_fa(nw);
if(!_cmp(_val[nw],_val[nx]))
std::swap(_val[nw],_val[nw]);
else
break;
nw=nx;
}
}
void pop()
{
swap(_val.front(),_val.back());
_val.pop_back();
int nw=0;
while(_son(nw,1)<=_val.size())
{
int nx=_son(nw,1);
for(std::size_t i=2;i<=Base;i++)
{
if(_son(nw,i)>=_val.size())
break;
if(_cmp(_val[_son(nw,i)],_val[nx]))
nx=_son(nw,i);
}
if(!_cmp(_val[nw],_val[nx]))
std::swap(_val[nw],_val[nx]);
else
break;
nw=nx;
}
}
std::size_t size()
{
return _val.size();
}
bool empty()
{
return _val.empty();
}
};
}
jqQt0220::heap<int,greater<int>,3> h;
int main()
{
___();
int _;
cin>>_;
while(_--)
{
int op;
cin>>op;
if(op==1)
{
int x;
cin>>x;
h.push(x);
}
if(op==2)
{
cout<<h.top()<<endl;
}
if(op==3)
{
h.pop();
}
}
return 0;
}
结果寄了,求调。