算法提高之选择最佳线路
-
核心思想:多源最短路
- 直接把所有源头发进队列做spfa就行
-
#include <iostream> #include <cstring> #include <algorithm> using namespace std; const int N = 1010,M = 40010,INF = 0x3f3f3f3f; int n,m,k; int dist[N]; bool st[N]; int h[N],e[M],ne[M],w[M],idx; int q[N]; void add(int a, int b, int c) { e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ; } void spfa() { int hh=0,tt=0; memset(dist,0x3f,sizeof dist); int scnt; cin>>scnt; for(int i=0;i<scnt;i++) //把所有源头放入队列 { int t; cin>>t; dist[t] = 0; st[t] = true; q[tt++] = t; } while(hh != tt) { int t = q[hh++]; if(hh == N) hh = 0; st[t] = false; for(int i=h[t];~i;i=ne[i]) { int j = e[i]; if(dist[j] > dist[t] + w[i]) { dist[j] = dist[t] + w[i]; if(!st[j]) { q[tt++] = j; if(tt == N) tt=0; st[j] = true; } } } } } int main() { while(cin>>n>>m>>k) { memset(h, -1, sizeof h); int p,res=INF; while(m--) { int a,b,c; cin>>a>>b>>c; add(a,b,c); } spfa(); if(dist[k] == INF) cout<<-1<<endl; else cout<<dist[k]<<endl; } }