迪杰斯特拉算法的实现

来源:互联网 发布:网络接入服务商怎么查 编辑:程序博客网 时间:2024/05/21 18:34

结合紫书的内容,实现的迪杰斯特拉算法,代码后面附上两个测试用例:

#include<iostream>#include<vector>#include<string>#include<set>#include<stack>#include<queue>#include<map>#include<algorithm>#include<cmath>#include<iomanip>#include<cstring>#include<sstream>#include<cstdio>#include<deque>#include<functional>using namespace std;typedef pair<int, int> pii;//距离 编号class Edge{public:int from, to, dist;};class Graph{//节点编号从1开始public:const int Inf = 0x3f3f3f3f;int n, m;vector<Edge> edge;vector<int> G[1000];bool visit[1005];int d[1005];int parent[1005];void Init(){memset(visit, false, sizeof(visit));memset(d,Inf,sizeof(d));memset(parent,-1,sizeof(parent));cin >> n >> m;for (int i = 0; i < m; i++){Edge temp;cin >> temp.from >> temp.to >> temp.dist;edge.push_back(temp);G[temp.from].push_back(edge.size()-1);//边的编号从0开始}}void Print(){cout << "result:" << endl;for (int j = 2; j <= n; j++){vector<int> res;res.push_back(j);int k = j;while (parent[k] != -1){int id = parent[k];res.push_back(edge[id].from);k = edge[id].from;}reverse(res.begin(),res.end());cout << d[j] << ": ";for (int i = 0; i < res.size(); i++){cout << res[i] << " ";}cout << endl;}}void Deal(int i){//从第i个点开始Init();priority_queue<pii, vector<pii>, greater<pii>> pq;pii temp;temp.first = 0; temp.second = i;pq.push(temp);d[i] = 0;while (!pq.empty()){temp = pq.top();pq.pop();if (visit[temp.second]) continue;visit[temp.second] = true;for (int j = 0; j < G[temp.second].size(); j++){int id = G[temp.second][j];int from = edge[id].from;int to = edge[id].to;if (d[to] > d[from] + edge[id].dist){d[to] = d[from] + edge[id].dist;pii t;t.first = d[to];t.second = to;parent[to] = id;pq.push(t);}}}Print();}};int main(){Graph g;g.Deal(1);system("pause");return 0;}/*test1:6 101 2 12 3 22 6 51 6 41 4 106 4 76 5 123 5 86 3 64 5 9test2:6 91 2 101 3 23 5 42 6 1002 4 204 6 304 5 32 3 53 4 1*/

原创粉丝点击