Dijkstra的算法,C ++,优先级队列,邻接列表

时间:2014-05-02 00:09:34

标签: c++ algorithm list graph queue

#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 Dijkstra(Vertices);


void makeGraph() {

    ifstream myFile;

    myFile.open("graph.txt");


    myFile >> nrVertices >> nrEdges;

    adj.resize(nrVertices+1);


    int nodeX, nodeY, weight;


    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));
    }
}

void printPath()
{
    for (vector<int>::iterator itr = weights.begin()+1; itr != weights.end(); ++itr) {
        cout <<  (*itr) << " "<<endl;
    }

}

void Dijkstra(Vertices startNode) {
    Vertices currVertex;

    weights[startNode.vertex] = 0;
    Q.push(startNode);

    while (!Q.empty()) {
        currVertex = Q.top();
        Q.pop();

        cout<<"Removed "<<&currVertex<<"from heap"<<endl;

        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() {

    makeGraph();
    Dijkstra(Vertices(1, 0));
    printPath();

    return 0;
}

所以这是我使用邻接列表实现Dijkstra算法的代码。输入:

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.依此类推。

然而,它打印出来:

Removed 0xbfb9d7a8from heap
Removed 0xbfb9d7a8from heap
0 
4 
2147483647 
2147483647 
2147483647 
2147483647 

当我需要它打印出来时:

V1: V2, 2; V4, 1
V2: v4, 3; V5, 10
V3: V1, 4; V6, 5
V4: V3, 2; V5, 2; V6, 8; V7, 4
V5: V7, 6
V6:
V7: V6, 1
Removed minimum 1 from heap
Print heap: V2, d=inf V4., d=inf v3, d= inf v7, d=inf v5......

请帮忙!!!!!

0 个答案:

没有答案