hdu-3790-最短路径问题(Dijkstra)
题目链接
1 /* 2 Name:hdu-3790-最短路径问题 3 Copyright: 4 Author: 5 Date: 2018/4/16 19:16:25 6 Description: 7 8 dijkstra 模板题 9 */ 10 #include <cstring> 11 #include <algorithm> 12 #include <iostream> 13 using namespace std; 14 const int MaxN = 1010; 15 const int INF = 0x3f3f3f3f; 16 int dis[MaxN], g[MaxN][MaxN],N, src, costEdge[MaxN][MaxN], cost[MaxN]; 17 bool v[MaxN]; 18 19 void dijkstra() { 20 for (int i=1; i<=N; i++){ 21 dis[i] = INF; 22 cost[i] = INF; 23 } 24 dis[src] = 0; 25 cost[src] = 0; 26 memset(v, 0, sizeof(v)); 27 for (int i=1; i<=N; i++) { 28 int mark = -1, mindis = INF; 29 for (int j=1; j<=N; ++j) { 30 if (!v[j] && dis[j]<mindis) { 31 mindis = dis[j]; 32 mark = j; 33 } 34 } 35 v[mark] = 1; 36 for (int j=1; j<=N; ++j) { 37 if (!v[j]) { 38 if (dis[mark] + g[mark][j] < dis[j]) { 39 dis[j] = dis[mark] + g[mark][j]; 40 cost[j] = cost[mark] + costEdge[mark][j]; 41 } else if(dis[mark] + g[mark][j] == dis[j] && cost[j] > cost[mark] + costEdge[mark][j]) { 42 cost[j] = cost[mark] + costEdge[mark][j]; 43 } 44 } 45 } 46 } 47 } 48 int final[MaxN]; 49 int main() 50 { 51 // freopen("in.txt", "r", stdin); 52 int m; 53 while (~scanf("%d %d", &N, &m) && (N || m)) { 54 memset(g, 0x3f, sizeof(g)); 55 memset(dis, 0, sizeof(dis)); 56 memset(cost, 0, sizeof(cost)); 57 memset(costEdge, 0x3f, sizeof(costEdge)); 58 59 for (int i=0; i<m; i++) { 60 int u, v, w, c; 61 scanf("%d %d %d %d", &u, &v, &w, &c); 62 if(w < g[u][v]) { //必须判断 重边否则WA 63 g[u][v] = g[v][u] = w; 64 costEdge[u][v] = costEdge[v][u] = c; 65 } 66 } 67 int final = 0; 68 scanf("%d %d", &src, &final); 69 dijkstra(); 70 printf("%d %d\n", dis[final], cost[final]); 71 } 72 return 0; 73 }