Priority_queue用法模板
Priority_queue用法模板
一、无需重载运算符
小根堆
#include<bits/stdc++.h>
using namespace std;
priority_queue<int,vector<int>,greater<int> >q;
int main()
{
for(int i=10;i>=1;i--)
q.push(i);
while(q.size())
{
cout<<q.top();
q.pop();
}
return 0;
}
输出结果:1 2 3 4 5 6 7 8 9 10
大根堆
#include<bits/stdc++.h>
using namespace std;
priority_queue<int>q;
int main()
{
for(int i=10;i>=1;i--)
q.push(i);
while(q.size())
{
cout<<q.top();
q.pop();
}
return 0;
}
输出结果:10 9 8 7 6 5 4 3 2 1
二、重载运算符
函数重载
#include<bits/stdc++.h>
using namespace std;
struct rec
{
int x,y;
};
priority_queue<rec>q;
//满足条件会放在堆底
bool operator<(rec a,rec b)
{
return a.x<b.x||(a.x==b.x&&a.y<b.y);
}
int main()
{
for(int i=10;i>=1;i--)
q.push({i%5,i%2});
while(q.size())
{
cout<<q.top().x<<' '<<q.top().y<<endl;
q.pop();
}
}
输出结果:
4 1
4 0
3 1
3 0
2 1
2 0
1 1
1 0
0 1
0 0
重载仿函数
#include<bits/stdc++.h>
using namespace std;
struct rec
{
int x,y;
};
//满足条件会放在堆底
struct cmp
{
bool operator()(rec a,rec b)
{
return a.x<b.x||(a.x==b.x&&a.y<b.y);
}
};
priority_queue<rec,vector<rec>,cmp>q;
int main()
{
for(int i=10;i>=1;i--)
{
q.push({i%5,i%2});
}
while(q.size())
{
cout<<q.top().x<<' '<<q.top().y<<endl;
q.pop();
}
}
输出结果:
4 1
4 0
3 1
3 0
2 1
2 0
1 1
1 0
0 1
0 0
友联函数
#include<bits/stdc++.h>
using namespace std;
struct rec
{
int x,y;
friend bool operator<(rec a,rec b)
{
return a.x<b.x||(a.x==b.x&&a.y<b.y);
}
};
//满足条件会放在堆底
priority_queue<rec>q;
int main()
{
for(int i=10;i>=1;i--)
{
q.push({i%5,i%2});
}
while(q.size())
{
cout<<q.top().x<<' '<<q.top().y<<endl;
q.pop();
}
}
输出结果:
4 1
4 0
3 1
3 0
2 1
2 0
1 1
1 0
0 1
0 0

浙公网安备 33010602011771号