Djikstra 最短路径算法的堆实现,C++
Heap implementation of Djikstra's Shortest-path algorithm, C++
>编辑:下面的代码运行良好,问题出在我的堆实现中。如果您正在寻找 Djikstra 最短路径算法的基于堆的版本C++实现,请随意查看。
在过去的几个小时里,我一直在尝试调试 Djikstra 最短路径算法(使用堆的 O(m*log(n) 版本)的实现,但仍然在测试用例的一小部分中遇到错误。我遇到问题的测试用例相当大(图中有 200 个节点),所以我不知道将其包含在这里有多大用处。可以说,我的实现似乎为除几个节点之外的所有节点生成了正确的最短路径。
对于任何算法专家,请您看看我有什么,并告诉我哪里出错了?
#include "Heap.h"
#include <sstream>
#include <string>
#include <sstream>
#include <iostream>
void ReadFile(std::vector<Edge> adjList[], std::string fileName);
const int NUM_VERTICES = 200;
const int START_VERTEX = 29;
int main(){
//valid entries in adjList start from[1] so that vertex #1 is stored in [1].
std::vector<Edge> adjList[NUM_VERTICES + 1];
std::vector<int> shortestPaths(NUM_VERTICES + 1);
ReadFile(adjList, "dijkstraData.txt");
//ReadFile(adjList, "test.txt");
Heap heap(NUM_VERTICES);
heap.InitializeForDjikstras();
HeapEntry min(0, 0);
//for each of the remaining vertices, process using Djikstra's greedy selection rule
for (int i = 0; i < NUM_VERTICES; i++){
shortestPaths[min.id] = min.key;
//recalculate keys of any nodes that now have edges crossing the boundary between X(processed) and V-X(unprocessed)
for (int q = 0; q < adjList[min.id].size(); q++){
int headID = adjList[min.id][q].id;
int costToHead = adjList[min.id][q].cost;
HeapEntry head = heap.Delete(headID);
if (head.key > shortestPaths[min.id] + costToHead) {
head.key = shortestPaths[min.id] + costToHead;
}
heap.Insert(head);
}
}
return 0;
}
如果看到我的堆实现或完整的 ReadFile 实现会有所帮助,请告诉我,我会发布它。我很确定它们工作正常。
问题实际上出在我的堆实现中。上面的代码是正确的,所以任何寻找 Djikstra 算法的堆实现的人都可以随意看看。
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的