Descriptionios
Input算法
Outputspa
Sample Inputcode
3 2 1 2 5 6 2 3 4 5 1 3 0 0
Sample Outputblog
9 11ip
經典迪傑斯卡爾算法求最短路徑,稍微加了一點小改動。適合像我這種入門的菜鳥!input
#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; }