[英]Why this Dijkstra algorithm is working without using min heap?
我仅使用 FIFO 队列实现了 Dijkstra 算法,但它仍然通过了 GFG 中的所有测试用例。 这段代码什么时候会失败或者如果它有效,那么为什么我们需要使用最小堆?
vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
{
// adj [] = {{{1, 9}}, {{0, 9}}}
vector<int> dist(V, INT_MAX);
queue<pair<int, int>> pq;
pq.push({0, S});
while(!pq.empty()) {
auto f = pq.front();
pq.pop();
int node = f.second;
int d = f.first;
if (d < dist[node])
{
dist[node] = d;
for(auto i: adj[node]) {
pq.push({d + i[1], i[0]});
}
}
}
return dist;
}
使用 FIFO 而不是最小堆仍然会给你正确的答案,但是你的程序找到答案的时间会更长。
为了引人注目,您需要提供一个大图作为输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.