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 (≤) 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 Input:
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
Sample Output:
0 2 3 3 40
#include<bits/stdc++.h> using namespace std; typedef long long ll; int m,s; int n; int d; int dis[1005] = {0}; int cs[1005] = {0}; int cost1[1005][1005] = {0}; int cost2[1005][1005] = {0}; int vis[1005] = {0}; int pre[1005] = {0}; void diji(int x){ fill(dis,dis+n,INT_MAX); fill(cs,cs+n,INT_MAX); dis[x] = 0; cs[x] = 0; for(int i=0;i < n;i++) pre[i] = i; while(1){ int minn = INT_MAX; int v = -1; for(int i=0;i < n;i++){ if(!vis[i]&&dis[i] < minn){ v = i; minn = dis[i]; } } if(v == -1)break; vis[v] = 1; for(int i=0;i < n;i++){ if(!vis[i]&&cost1[i][v]!=INT_MAX){ if(dis[v]+cost1[v][i] < dis[i]){ dis[i] = dis[v]+cost1[v][i]; pre[i] = v; cs[i] = cs[v] + cost2[v][i]; } else if(dis[v]+cost1[v][i] == dis[i]&&cs[v]+cost2[v][i] < cs[i]){ pre[i] = v; cs[i] = cs[v] + cost2[v][i]; } } } } } vector<int> path; void dfs(int v){ if(v==s){ path.push_back(v); return; } dfs(pre[v]); path.push_back(v); } int main(){ cin >> n >> m >> s >> d; for(int i=0;i < n;i++){ for(int j=0;j < n;j++){ cost1[i][j] = INT_MAX; cost1[i][i] = 0; } } for(int i=0;i < m;i++){ int x,y,a,b; cin >> x >> y >> a >> b; cost1[x][y] = a; cost1[y][x] = a; cost2[x][y] = b; cost2[y][x] = b; } diji(s); dfs(d); for(int i=0;i < path.size();i++){ cout << path[i] << " "; } cout << dis[d] << " " << cs[d]; return 0; }
——好难。。图论太差了