最短路演算法優化(dijkstra演算法+鄰接表+佇列優化,bellman演算法+鄰接表+佇列優化)
阿新 • • 發佈:2018-12-19
dijkstra演算法+鄰接表+佇列優化:
#include<bits/stdc++.h> using namespace std; const int M=1000000000; struct node { int to,cost; friend bool operator <(node a,node b) { return a.cost>b.cost; } }; vector<node>G[10005]; bool vis[10005]; int n,m,x,s,t; int d[10005]; void Dij(){ fill(d+1,d+n+1,M); vis[s]=1; d[s]=0; priority_queue<node>Q; Q.push((node){s,0}); while(!Q.empty()){ node x=Q.top();Q.pop(); int u=x.to; if(vis[u])continue; vis[u]=1; for(int i=0;i<G[u].size();i++){ node e=G[u][i]; if(d[e.to]>d[u]+e.cost){ d[e.to]=d[u]+e.cost; Q.push((node){e.to,d[e.to]}); } } } } int main(){ cin>>n>>m>>s>>t; for(int i=1;i<=m;i++){ node 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; /* 5 5 1 5 1 2 20 2 3 30 3 4 20 4 5 20 1 5 100 */ }
bellman演算法+鄰接表+佇列優化:
#include<bits/stdc++.h> using namespace std; const int M=1000000000; struct node { int to,cost; friend bool operator <(node a,node b) { return a.cost>b.cost; } }; vector<node>G[10005]; bool vis[10005]; int n,m,x,s,t; int d[10005]; void bellman(int s){ fill(d+1,d+n+1,M); fill(vis,vis+n+1,false); d[s]=0; vis[s]=1; priority_queue<node>Q; Q.push((node){s,0}); while(!Q.empty()){ node x=Q.top();Q.pop(); cout<<x.to<<' '<<x.cost<<endl; for(int i=0;i<G[x.to].size();i++) { node e=G[x.to][i];//x.to的出邊 if(d[e.to]>d[x.to]+e.cost) { d[e.to]=d[x.to]+e.cost; if(!vis[e.to]) { Q.push((node){e.to,d[e.to]}); vis[e.to]=1; } } } } } int main(){ cin>>n>>m>>s>>t; for(int i=1;i<=m;i++){ node e; scanf("%d%d%d",&x,&e.to,&e.cost); G[x].push_back(e); } for(int i=1;i<=5;i++) { for(int j=0;j<G[i].size();j++) { cout<<G[i][j].to<<' '<<G[i][j].cost<<endl; } } bellman(s); if(d[t]==M)printf("-1"); else printf("%d",d[t]); return 0; /* 5 5 1 5 1 2 20 2 3 30 3 4 20 4 5 20 1 5 100 */ }
如果一個點進入佇列的次數超過n次,說明存在負環