Description
給你n個點,m條無向邊,每條邊都有長度d和花費p,給你起點s終點t,要求輸出起點到終點的最短距離及其花費,如果最短距離有多條路線,則輸出花費最少的。
Input
輸入n,m,點的編號是1~n,然后是m行,每行4個數 a,b,d,p,表示a和b之間有一條邊,且其長度為d,花費為p。最后一行是兩個數 s,t;起點s,終點t。n和m為0時輸入結束。
(1<n<=1000, 0<m<100000, s != t)
(1<n<=1000, 0<m<100000, s != t)
Output
輸出 一行有兩個數, 最短距離及其花費。
Sample Input
3 2 1 2 5 6 2 3 4 5 1 3 0 0
Sample Output
9 11
經典迪傑斯卡爾算法求最短路徑,稍微加了一點小改動。適合像我這種入門的菜鳥!
#include <iostream> #include <algorithm> #include <cstring> #include <cstdio> #include <cctype> #include <cstdlib> #include <stack> #include <cmath> #include <queue> #define INF 0xffffff using namespace std; const int maxn = 1010 ; int n, m, s, t, a, b, d, p; int G[maxn][maxn];//距離 int pd[maxn][maxn];//金錢 int dis[maxn];//距離 int sp[maxn];//花費 bool vis[maxn];//記錄是否走過 void Dij(){ dis[s] = 0 ; sp[s] = 0 ; for(int k=1; k<=n; k++){ int Min = INF ; int ind = -1 ; for(int i=1; i<=n; i++){ if( !vis[i] && dis[i]<Min){ ind = i ; Min = dis[i]; } } vis[ind] = true; for(int j=1; j<=n; j++){ if( !vis[j] && dis[ind]+G[ind][j]<dis[j]){ dis[j] = dis[ind] + G[ind][j]; sp[j] = sp[ind] + pd[ind][j]; } else if( !vis[j] && dis[j] == dis[ind]+G[ind][j] ){ sp[j] = min(sp[j],sp[ind]+pd[ind][j]); } } } } int main(){ while( scanf("%d %d",&n, &m) !=EOF ){ if( n == 0 && m == 0 ) break; for(int i=1; i<=n; i++){ vis[i] = false ; sp[i] = INF ; dis[i] = INF ; for(int j=1; j<=n; j++){ G[i][j] = INF ; } } while( m -- ){ scanf("%d %d %d %d",&a, &b, &d, &p); G[a][b] = G[b][a] = d ; pd[a][b] = pd[b][a] = p ; } scanf("%d %d", &s, &t); Dij(); cout << dis[t] << " " << sp[t] << endl ; } return 0; }