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 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 <iostream>
#include <fstream>
#include <vector>
#define N 505
#define INF 0x7fffffff
#define min(x, y) x < y ? x : y
using namespace std;
struct Node{
int no, dis, cos;
};
vector<Node> node[N];
int path[N];
bool mark[N];
int dist[N], cost[N];
void DFS(int dest)
{
if(path[dest] == -1)
return;
DFS(path[dest]);
cout << path[dest] << " ";
}
int main()
{
ifstream cin("in.txt");
int n, m, s, d;
while(cin >> n >> m >> s >> d)
{
for(int i = 0; i < n; ++i)
{
node[i].clear();
path[i] = -1;
mark[i] = false;
dist[i] = cost[i] = INF;
}
for(int i = 0; i < m; ++i)
{
int a, b, dis, cos;
Node tmp;
cin >> a >> b >> dis >> cos;
tmp.no = b;
tmp.dis = dis;
tmp.cos = cos;
node[a].push_back(tmp);
tmp.no = a;
node[b].push_back(tmp);
}
int newP = s;
dist[newP] = 0;
cost[newP] = 0;
mark[newP] = true;
for(int i = 1; i < n; ++i)
{
for(int j = 0; j < node[newP].size(); ++j)
{
int no = node[newP][j].no;
int dis = node[newP][j].dis;
int cos = node[newP][j].cos;
if(mark[no] == true)
continue;
if(dist[no] == INF || dist[no] > dist[newP] + dis || (dist[no] == dist[newP] + dis && cost[no] > cost[newP] + cos))
{
dist[no] = dist[newP] + dis;
cost[no] = cost[newP] + cos;
path[no] = newP;
}
}
int maxDis = INF;
int maxCost = INF;
for(int j = 0; j < n; ++j)
{
if(dist[j] == INF || mark[j] == true)
continue;
if(dist[j] < maxDis || (dist[j] == maxDis && cost[j] < maxCost))
{
maxDis = dist[j];
maxCost = cost[j];
newP = j;
}
}
mark[newP] = true;
}
DFS(d);
cout << d << " " << dist[d] << " " << cost[d];
}
return 0;
}