自定义🟧小根堆🟧🟩哈希表🟩
🚀1. 小根堆
#include<queue>
#include<vector>
🪁1.1 内置数据类型
🌈1.1.1 小根堆
// PII
typedef pair<int,int> PII;
priority_queue<int,vector<int>,greater<int>> heap;
priority_queue<PII,vector<PII>,greater<PII>> heap;// 按照pair里第一个数据排序
🌈1.1.2 大根堆
// PII
typedef pair<int,int> PII;
priority_queue<int,vector<int>,less<int>> heap;
priority_queue<PII,vector<PII>,less<PII>> heap;// 按照pair里第一个数据排序
🪁1.2 自定义数据类型
需要自定义比较函数对象代替原先的greater<int>,less<int>
一般写法:
#include<queue>
#include<vector>
using namespace std;
struct Edge
{
int a,b,w;
};
struct cmp
{
bool operator()(Edge &a,Edge &b)
{
return a.w>b.w;
}
};
priority_queue<Edge,vector<Edge>,cmp> heap;
🚀2. 哈希表
🔎 2.1 unordered_set
哈希表的基本用法还是很简单的,但是最近写题目时遇到了需要使用
unordered_set<PII> set的用法😢,上网搜集了一个好方法
unordered_set<type,hashfunc,eqfunc>
✔️ type:数据类型
✔️ hashfunc: 哈希函数
✔️ eqfunc: 相等判断函数
🟩大致写法如下:
#include <iostream>
#include <unordered_set>
using namespace std;
struct Edge
{
int a,b;
Edge(int a,int b):a(a),b(b){}
};
struct hashfunc
{
size_t operator()(const Edge &e)const
{
return e.a * e.b;
}
};
struct eqfunc
{
bool operator()(const Edge &x,const Edge &y)const
{
return x.a == y.a && x.b == y.b;
}
};
unordered_set<Edge,hashfunc,eqfunc> s;
int main()
{
s.insert(Edge(2,3));
cout << s.count(Edge(3,2)) << endl;
cout << s.count(Edge(2,3)) << endl;
return 0;
}
🟥注:eqfunc在自定义结构体时是必须用到的,但是如果是pair类型,可以省略.
#include <iostream>
#include <unordered_set>
using namespace std;
typedef pair<int,int> PII;
struct hashfunc
{
size_t operator()(const PII &e)const
{
return e.first * e.second;
}
};
unordered_set<PII,hashfunc> s;
int main()
{
s.insert({1,2});
cout<<s.count({2,3})<<endl;
return 0;
}
🔎 2.2 unordered_map
同理可得,大致上是差不多吧😊
unoedered_map<key_type,value_type,hashfunc,eqfunc>
🟥 key_type:键的类型
🟥 key_value : 值的类型
一个小小的例子,以后遇到了相似的问题再补充(╯°□°)╯︵ ┻━┻
struct hashfunc
{
size_t operator()(const PII &e)const
{
return e.first * e.second;
}
};
unordered_map<PII,int,hashfunc> s;
效果如下:⬇️⬇️
s[{1,2}]=2

浙公网安备 33010602011771号