Dijkstra(鄰接表實現)
阿新 • • 發佈:2019-01-01
#include<iostream> #include<string.h> #include<vector> #include<queue> using namespace std; #define INF 0x3f3f3f3f #define Max_N 1000 struct edge{int to,cost;}; typedef pair<int,int> P; //first為到S最短距離,second為頂點編號 int V,E; vector<edge> G[Max_N]; //每個G[v]裡面包含一個邊的edge型別vector,記錄與頂點v相連的點和他們組成邊的權值 int d[Max_N]; void dijkstra(int s) { //創造優先佇列que priority_queue<P,vector<P>,greater<P> > que;//最後兩個>間有同一個空格,對於pair的P,預設first為排序依據 fill(d,d+V,INF); d[s]=0; que.push(P(0,s)); while(!que.empty()) { P p=que.top(); que.pop(); int v=p.second; if(d[v]<p.first) continue; //原來的值更小,不更新,跳過 for(int i=0;i<G[v].size();i++) //遍歷與頂點v相連的邊 { edge e=G[v][i]; if(d[e.to]>d[v]+e.cost) { d[e.to]=d[v]+e.cost; que.push(P(d[e.to],e.to)); } } } } int main() { //freopen("dijkstra.txt","r",stdin); //錄入有向權圖,起點S預設為第一個錄入頂點 cin>>V>>E; for(int i=0;i<E;i++) { int s,t,co; //s為起點,t為終點,co為權 cin>>s>>t>>co; G[s].push_back({t,co}); } // dijkstra(0); for(int i=1;i<V;i++) cout<<"S到序號"<<i<<"頂點的最短距離:"<<d[i]<<endl; }