1. 程式人生 > >暢通工程續

暢通工程續

%d pre nbsp 計劃 lse 題目 sam 之間 con

Problem Description 某省自從實行了很多年的暢通工程計劃後,終於修建了很多路。不過路多了也不好,每次要從一個城鎮到另一個城鎮時,都有許多種道路方案可以選擇,而某些方案要比另一些方案行走的距離要短很多。這讓行人很困擾。

現在,已知起點和終點,請你計算出要從起點到終點,最短需要行走多少距離。 Input 本題目包含多組數據,請處理到文件結束。
每組數據第一行包含兩個正整數N和M(0<N<200,0<M<1000),分別代表現有城鎮的數目和已修建的道路的數目。城鎮分別以0~N-1編號。
接下來是M行道路信息。每一行有三個整數A,B,X(0<=A,B<N,A!=B,0<X<10000),表示城鎮A和城鎮B之間有一條長度為X的雙向道路。
再接下一行有兩個整數S,T(0<=S,T<N),分別代表起點和終點。 Output 對於每組數據,請在一行裏輸出最短需要行走的距離。如果不存在從S到T的路線,就輸出-1. Sample Input 3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2 Sample Output 2 -1
 1
#include<iostream> 2 #include<queue> 3 #include<cstdio> 4 #include<cstring> 5 using namespace std; 6 #include<vector> 7 const int maxn = 205; 8 vector <pair<int, int> > E[maxn]; 9 int dis[maxn]; 10 int n, m,s,t; 11 void init() 12 { 13 for (int i = 0
; i < maxn; i++) 14 E[i].clear(), dis[i] = 1e9; 15 } 16 void dit() 17 { 18 dis[s] = 0; 19 priority_queue<pair<int, int> > q; 20 q.push(make_pair(-dis[s], s)); 21 while (!q.empty()) 22 { 23 int te = q.top().second; 24 q.pop(); 25 for (int
i = 0; i < E[te].size(); i++) 26 { 27 int d = E[te][i].first; 28 int k = E[te][i].second; 29 if (dis[d] > dis[te] + k) 30 { 31 dis[d] = dis[te] + k; 32 q.push(make_pair(-dis[d], d)); 33 } 34 } 35 } 36 if (dis[t] == 1e9) 37 cout << "-1" << endl; 38 else cout << dis[t] << endl; 39 } 40 int main() 41 { 42 while (cin >> n >> m) 43 { 44 init(); 45 for (int i = 0; i < m; i++) 46 { 47 int t1, t2, t3; 48 scanf("%d %d %d", &t1, &t2, &t3); 49 E[t1].push_back(make_pair(t2, t3)); 50 E[t2].push_back(make_pair(t1, t3)); 51 } 52 scanf("%d %d", &s, &t); 53 dit(); 54 } 55 return 0; 56 }

暢通工程續