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
Process
很简单的dfs…
链式向前星不懂的点这里:图的存储模式——链式向前星 蒟蒻建议不懂链式向前星的同学可以花两分钟时间学一下,真的比一般的图存储方式好太多了,不仅好用还省空间。
Code
#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f
int cnt, head[100000], n, m, beginn, endd, mind = INF, minc = INF, vis[100000];
struct node
{
int to, next, dis, cost;
}a[100000];
vector<int> v, tempv;
void add(int u, int v, int w1, int w2)
{
a[cnt].to = v;
a[cnt].dis = w1;
a[cnt].cost = w2;
a[cnt].next = head[u];
head[u] = cnt++;
}
void dfs(int cur, int diss, int costt)
{
if (cur == endd && (diss < mind || (diss == mind && costt < minc)))//三重判定(重点)
{
v.clear();
for (int i : tempv)
v.push_back(i);
mind = diss;
minc = costt;
return;
}
for (int i = head[cur]; i; i = a[i].next)
{
if (vis[a[i].to] == 0)
{
vis[a[i].to] = 1;
tempv.push_back(a[i].to);
dfs(a[i].to, diss + a[i].dis, costt + a[i].cost);
tempv.pop_back();
vis[a[i].to] = 0;
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin >> n >> m >> beginn >> endd;
for (int i = 0; i < m; i++)//链式向前星存图
{
int u, v, w1, w2;
cin >> u >> v >> w1 >> w2;
add(u, v, w1, w2);
add(v, u, w1, w2);
}
vis[beginn] = 1;
dfs(beginn, 0, 0);
cout << beginn << " ";
for (int i : v)
cout << i << " ";
cout << mind << " " << minc;
return 0;
}