queue<int> q
// BFS 广度优先搜索
q.push(start)
visited[start] = true
while not q.empty():
cur = q.front()
q.pop()
for each neighbor of cur:
if not visited[neighbor]:
visited[neighbor] = true
q.push(neighbor)
// 约瑟夫环
queue<int> circle
for i from 1 to n:
circle.push(i)
while not circle.empty():
for i from 1 to m - 1:
circle.push(circle.front())
circle.pop()
print circle.front()
circle.pop()
// 默认大根堆
priority_queue<int> maxHeap
// 小根堆
priority_queue<int, vector<int>, greater<int>> minHeap
// 自定义比较器
struct Compare { bool operator()(int a, int b) { return a > b; } }
priority_queue<int, vector<int>, Compare> pq
伪代码示例
// 合并果子(小根堆)
priority_queue<int, vector<int>, greater<int>> pq
for each x in fruits:
pq.push(x)
total = 0
while pq.size() > 1:
a = pq.top(); pq.pop()
b = pq.top(); pq.pop()
total += a + b
pq.push(a + b)
// Dijkstra 堆优化
priority_queue<{dist, node}, vector, greater> pq
dist[start] = 0
pq.push({0, start})
while not pq.empty():
{d, u} = pq.top(); pq.pop()
if d != dist[u]: continue
for each {v, w} of u:
if dist[v] > dist[u] + w:
dist[v] = dist[u] + w
pq.push({dist[v], v})