【发布时间】:2014-05-01 03:44:58
【问题描述】:
#include <iostream>
#include <fstream>
#include <functional>
#include <climits>
#include <vector>
#include <queue>
#include <list>
using namespace std;
struct Vertices {
int vertex;
int weight;
Vertices(int v, int w) : vertex(v), weight(w) { };
Vertices() { }
};
class CompareGreater {
public:
bool const operator()(Vertices &nodeX, Vertices &nodeY) {
return (nodeX.weight > nodeY.weight) ;
}
};
vector< list<Vertices> > adj;
vector<int> weights;
priority_queue<Vertices, vector<Vertices>, CompareGreater> Q;
int nrVertices, nrEdges;
void readData();
void Dijkstra(Vertices);
void writeData();
void writeData() {
ifstream out;
out.open("graph.txt");
weights.resize(1);
for (vector<int>::iterator it = weights.begin()+1; it != weights.end(); ++it) {
cout << (*it) << " ";
}
out.close();
}
void readData() {
ifstream myFile;
myFile.open("graph.txt");
int nodeX, nodeY, weight;
myFile >> nrVertices >> nrEdges;
adj.resize(nrVertices+1);
weights.resize(1);
for (int i = 1; i <= nrVertices; ++i) {
weights.push_back(INT_MAX);
}
for (int i = 1; i <= nrEdges; ++i) {
myFile >> nodeX >> nodeY >> weight;
adj[nodeX].push_back(Vertices(nodeY, weight));
}
myFile.close();
}
void Dijkstra(Vertices startNode) {
Vertices currVertex;
weights[startNode.vertex] = 0;
Q.push(startNode);
while (!Q.empty()) {
currVertex = Q.top();
Q.pop();
if (currVertex.weight <= weights[currVertex.vertex]) {
for (list<Vertices>::iterator it = adj[currVertex.vertex].begin(); it != adj[currVertex.vertex].end(); ++it) {
if (weights[it->vertex] > weights[currVertex.vertex] + it->weight) {
weights[it->vertex] = weights[currVertex.vertex] + it->weight;
Q.push(Vertices((it->vertex), weights[it->vertex]));
}
}
}
}
}
int main() {
readData();
Dijkstra(Vertices(1, 0));
writeData();
return 0;
}
所以这就是我到目前为止为了实现具有邻接列表的 Dijkstra 算法。但是,我的代码不会打印任何内容。有什么帮助吗?
Graph.txt 如下所示:
7
2
2 2
4 1
2
4 3
5 10
2
1 4
6 5
4
3 2
5 2
6 8
7 4
1
7 6
0
1
6 1
这意味着从顶点 1 到 7 依次存在 7 个顶点。 顶点 1 有 2 条边,一条连接到顶点 2,权重为 2,第二条连接到顶点 4,权重为 1。 顶点 2 有 2 条边,第一个到顶点 4,权重为 3,第二个到顶点 5,权重为 10。 顶点 3 有 2 条边,第一个到顶点 1,权重为 4,第二个到顶点 6,权重为 5。 等等。
【问题讨论】:
标签: c++ algorithm list queue priority-queue