题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805464397627392
题目描述
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.
输入
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.
输出
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.
样例输入
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
样例输出
0 2 3 3 40
代码
#include <bits/stdc++.h>
using namespace std;
//n<=500可用邻接矩阵表示
const int maxn = 510;
const int INF = 0x3f3f3f3f;
int n,m;
int G[maxn][maxn]; //存距离
int cost[maxn][maxn]; //存花费
int d[maxn], c[maxn]; //存最短距离和最短花费
int pre[maxn]; //pre[u]=v v是u在最短路径中的前一个节点
bool vis[maxn];
//d[] s到每一点的最短距离
void Dijkstra(int s)
{
vis[s] = true;
fill(vis, vis + maxn, false);
fill(d, d + maxn, INF);
fill(c, c + maxn, INF);
d[s] = 0;
c[s] = 0;
for(int i = 0; i < n; ++i) pre[i] = i;
for(int i = 0; i < n; ++i){
if(vis[i]) continue;
//找未访问节点中d[]最小的
int minn = INF, u = -1;
for(int j = 0; j < n; ++j){
if(!vis[j] && d[j] < minn){
minn = d[j];
u = j;
}
}
if(u == -1) return;
vis[u] = true;
for(int v = 0; v < n; ++v){
if(!vis[v] && G[u][v] != INF){
if(d[u] + G[u][v] < d[v]){
d[v] = d[u] + G[u][v];
c[v] = c[u] + cost[u][v];
pre[v] = u;
}
else if(d[u] + G[u][v] == d[v] && c[u] + cost[u][v] < c[v]){
c[v] = c[u] + cost[u][v];
pre[v] = u;
}
}
}
}
}
//递归求最短路径
void DFS(int s, int v)
{
if(v == s){
printf("%d ",v);
return;
}
DFS(s, pre[v]);
printf("%d ",v);
}
int main()
{
int s,e;
fill(G[0], G[0] + maxn * maxn, INF);//首地址,尾地址,初始化的值
//fill(cost[0], cost[0] + maxn * maxn, INF); //cost数组其实不必初始化
scanf("%d%d%d%d",&n,&m,&s,&e);
for(int i = 0; i < m; ++i){
int a,b,dis,cos;
scanf("%d%d%d%d",&a,&b,&dis,&cos);
G[a][b] = G[b][a] = dis;
cost[a][b] = cost[b][a] = cos;
}
Dijkstra(s);
DFS(s, e);
printf("%d %d",d[e], c[e]);
return 0;
}