Dijkstra演算法(鄰接表+優先佇列優化)
阿新 • • 發佈:2019-02-10
Dijkstra演算法是在圖論中應用很廣的一種演算法,它本質上是貪心的成功應用。它可以求加權圖的單源最短路。
但是如果不優化的話,它的複雜度是O(n方),比較低效,一般我們採用鄰接表+優先佇列的優化。
#include<bits/stdc++.h> using namespace std; const int M=1000000000; struct HeadNode{ int d,u; bool operator < (const HeadNode& rhs) const{ return d>rhs.d; } }; struct edge{ int to; int cost; }; vector<edge>G[10005]; bool vis[10005]; int n,m,x,s,t; int d[10005]; void Dij(){ fill(d+1,d+n+1,M); d[s]=0; priority_queue<HeadNode>Q; Q.push((HeadNode){0,s}); while(!Q.empty()){ HeadNode x=Q.top();Q.pop(); int u=x.u; if(vis[u])continue; vis[u]=1; for(int i=0;i<G[u].size();i++){ edge e=G[u][i]; if(d[e.to]>d[u]+e.cost){ d[e.to]=d[u]+e.cost; Q.push((HeadNode){d[e.to],e.to}); } } } } int main(){ cin>>n>>m>>s>>t; for(int i=1;i<=m;i++){ edge e; scanf("%d%d%d",&x,&e.to,&e.cost); G[x].push_back(e); } Dij(); if(d[t]==M)printf("-1"); else printf("%d",d[t]); return 0; }