1030. Travel Plan (30)
A traveler's map gives the distances between cities along the highways, together with the cost of each highway. Now you are supposed to write a program to help a traveler to decide the shortest path between his/her starting city and the destination. If such a shortest path is not unique, you are supposed to output the one with the minimum cost, which is guaranteed to be unique.
Input Specification:
Each input file contains one test case. Each case starts with a line containing 4 positive integers N, M, S, and D, where N (<=500) is the number of cities (and hence the cities are numbered from 0 to N-1); M is the number of highways; S and D are the starting and the destination cities, respectively. Then M lines follow, each provides the information of a highway, in the format:
City1 City2 Distance Cost
where the numbers are all integers no more than 500, and are separated by a space.
Output Specification:
For each test case, print in one line the cities along the shortest path from the starting point to the destination, followed by the total distance and the total cost of the path. The numbers must be separated by a space and there must be no extra space at the end of output.
Sample Input4 5 0 3 0 1 1 20 1 3 2 30 0 3 4 10 0 2 2 20 2 3 1 20Sample Output
0 2 3 3 40
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> using namespace std; #define maxn 510 #define inf 0x3f3f3f3f int edge[maxn][maxn]; int cost[maxn][maxn]; int n, m, s,e; int dis[maxn]; int vis[maxn]; int dcos[maxn]; int pre[maxn]; void dijs(int sc, int en) {for(int i = 0; i < n; i++){dis[i] = edge[sc][i];dcos[i] = cost[sc][i];}memset(vis, 0, sizeof(vis));memset(pre, -1, sizeof(pre));vis[sc] = 1;for(int i = 1; i < n; i++){int dismin = inf, u = -1;for(int j = 0; j < n; j++){if(vis[j] == 0 && dismin > dis[j]){dismin = dis[j];u = j;}}vis[u] = 1; // printf("%d-->%d\n", i, u);for(int j = 0; j < n; j++){if(vis[j] == 0 && edge[u][j] != inf){if(dis[j] > dis[u] + edge[u][j]){dis[j] = dis[u] + edge[u][j];dcos[j] = dcos[u] + cost[u][j];pre[j] = u;}else if(dis[j] == dis[u] + edge[u][j] && dcos[j] > dcos[u] + cost[u][j]){dis[j] = dis[u] + edge[u][j];dcos[j] = dcos[u] + cost[u][j];pre[j] = u;}}}} } int main() {scanf("%d%d%d%d",&n, &m, &s, &e);for(int i = 0; i < n; i++){for(int j = 0; j < n; j++){edge[i][j] = edge[j][i] = (i == j) ? 0 : inf;cost[i][j] = edge[j][i] = (i == j) ? 0 : inf;}}for(int i = 0; i < m; i++){int a, b, c,d;cin>>a>>b>>c>>d;edge[a][b] = edge[b][a] = c;cost[a][b] = cost[b][a] = d;}dijs(s, e);int tmp[maxn];int cnt = 0;tmp[cnt++] = e;int pos = e;while(pre[pos] != -1){tmp[cnt++] = pre[pos];pos = pre[pos];}tmp[cnt++] = s;for(int i = cnt - 1; i >= 0; i--)cout<<tmp[i]<<" ";cout<<dis[e]<<" "<<dcos[e]<<endl;}