1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
| #include<bits/stdc++.h> using namespace std; const int MAX = 1000; const int INF = 0x3f3f3f3f;
int n,m,s,t; int len[MAX][MAX],tim[MAX][MAX]; int dist1[MAX],cost1[MAX],path1[MAX]; int sum2[MAX],cost2[MAX],path2[MAX]; bool visited[MAX];
void Dijkstra1(){ memset(visited,0,sizeof(visited)); for(int i = 0 ; i < n ; i ++){ dist1[i] = len[s][i]; cost1[i] = tim[s][i]; if(len[s][i] != INF) path1[i] = s; else path1[i] = i; } visited[s] = true; for(int i = 0 ; i < n-1 ; i ++){ int f = -1; int min_ = INF; for(int j = 0 ; j < n ; j ++){ if(!visited[j] && dist1[j] < min_){ min_ = dist1[j]; f = j; } } visited[f] = true; for(int j = 0 ; j < n ; j ++){ if(!visited[j] && dist1[j] > dist1[f] + len[f][j]){ dist1[j] = dist1[f] + len[f][j]; cost1[j] = cost1[f] + tim[f][j]; path1[j] = f; }else if(!visited[j] && dist1[j] == dist1[f] + len[f][j] && cost1[j] > cost1[f] + tim[f][j]){ dist1[j] = dist1[f] + len[f][j]; cost1[j] = cost1[f] + tim[f][j]; path1[j] = f; } } } }
void Dijkstra2(){ memset(visited,0,sizeof(visited)); for(int i = 0 ; i < n ; i ++){ cost2[i] = tim[s][i]; if(len[s][i] != INF){ path2[i] = s; sum2[i] = 1; } else path2[i] = i; } visited[s] = true; for(int i = 0 ; i < n-1 ; i ++){ int f = -1; int min_ = INF; for(int j = 0 ; j < n ; j ++){ if(!visited[j] && cost2[j] < min_){ min_ = cost2[j]; f = j; } } visited[f] = true; for(int j = 0 ; j < n ; j ++){ if(!visited[j] && cost2[j] > cost2[f] + tim[f][j]){ cost2[j] = cost2[f] + tim[f][j]; sum2[j] = sum2[f] + 1; path2[j] = f; }else if(!visited[j] && cost2[j] == cost2[f] + tim[f][j] && sum2[j] > sum2[f] + 1){ cost2[j] = cost2[f] + tim[f][j]; sum2[j] = sum2[f] + 1; path2[j] = f; } } } }
void PrintPath(int x, int ty){ if(x == s){ cout<<s; return; } if(ty == 1) PrintPath(path1[x], ty); else PrintPath(path2[x], ty); cout<<" -> "; cout<<x; }
int main(void){ cin>>n>>m; memset(len,INF,sizeof(len)); memset(tim,INF,sizeof(tim)); for(int i = 0 ; i < m ; i ++){ int a,b,f,d,ti;cin>>a>>b>>f>>d>>ti; if(f){ len[a][b] = d; tim[a][b] = ti; }else{ len[a][b] = len[b][a] = d; tim[a][b] = tim[b][a] = ti; } } cin>>s>>t; Dijkstra1(); Dijkstra2(); bool same = true; int a = t;int b = t; while(a != s && b != s){ if(a != b){ same = false; break; } a = path1[a]; b = path2[b]; } if(same){ cout<<"Distance = "<<dist1[t]<<"; "<<"Time = "<<cost2[t]<<": "; PrintPath(t,1); }else{ cout<<"Distance = "<<dist1[t]<<": "; PrintPath(t,1);cout<<endl; cout<<"Time = "<<cost2[t]<<": "; PrintPath(t,2);cout<<endl; } return 0; }
|