Dijkstra算法(两种写法)

来源:互联网 发布:淘宝入驻条件及费用 编辑:程序博客网 时间:2024/06/05 13:22
<span style="font-size:14px;">//Dijkstra_001.cpp -- 单源最短路#include <iostream>#include <algorithm>#include <cstring>#include <cstdlib>#include <cstdio>#include <cmath>#include <queue>#include <vector>#include <map>typedef long long ll;using namespace std;const int INF = 0x3f3f3f3f;const int maxE = 1000 + 10;const int maxV = 100 + 10;/*int cost[maxV][maxV];int d[maxV];bool used[maxV];int V;void Dijkstra(int s){fill(d, d+V, INF);memset(used, 0, sizeof(used));d[s] = 0;while( 1 ){int v = -1;// 从尚未使用过的顶点中选择一个距离最小的顶点for( int i=0; i<V; i++ ){if( !used[i] && (v==-1 || d[i]<d[v]) )i = v;}if( v==-1 )break;used[v] = true;for( int i=0; i<V; i++ )d[i] = min(d[i], d[v]+cost[v][i]);}}*/struct edge{int to, cost;};typedef pair<int, int> P;// first是最短距离,second是顶点的编号int V, E;vector<edge> G[maxV];int d[maxV];void Dijkstra(int s){// 通过指定greater<P>参数,堆按照first从小到大的顺序取出值。priority_queue<P, vector<P>, greater<P> > pque;fill(d, d+V, INF);d[s] = 0;pque.push(P(0, s));while( !pque.empty() ){P p = pque.top();pque.pop();int v = p.second;if( d[v]<p.first )continue;// 只有小于或等于两种情况for( int i=0; i<G[v].size(); i++ ){edge e = G[v][i];if( d[e.to]>d[v]+e.cost ){d[e.to] = d[v] + e.cost;pque.push(P(d[e.to], e.to));}}}}int main(void){cin>>V>>E;int a, b, c;for( int i=0; i<E; i++ ){cin>>a>>b>>c;G[a].push_back((edge){b,c});G[b].push_back((edge){a,c});}Dijkstra(0);for( int i=0; i<V; i++ )cout<<i<<' '<<d[i]<<endl;return 0;}</span>

0 0
原创粉丝点击