7-9 旅游规划 (25分)
有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。
输入格式:
输入说明:输入数据的第1行给出4个正整数N、M、S、D,其中N(2≤N≤500)是城市的个数,顺便假设城市的编号为0~(N−1);M是高速公路的条数;S是出发地的城市编号;D是目的地的城市编号。随后的M行中,每行给出一条高速公路的信息,分别是:城市1、城市2、高速公路长度、收费额,中间用空格分开,数字均为整数且不超过500。输入保证解的存在。
输出格式:
在一行里输出路径的长度和收费总额,数字间以空格分隔,输出结尾不能有多余空格。
输入样例:
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
输出样例:
3 40
题解:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 510;
bool vis[maxn];
int n, m, s, t, g[maxn][maxn], p[maxn][maxn];
struct node { int dis, money; } cost[maxn];
inline const int read()
{
int x = 0, f = 1; char ch = getchar();
while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + ch - '0'; ch = getchar(); }
return x * f;
}
void dijkstra(int src, int des)
{
cost[src].dis = cost[src].money = 0;
for (int i = 0; i < n - 1; i++)
{
int u = 0, dis = inf;
for (int j = 0; j < n - 1; j++)
{
if (!vis[j] && cost[j].dis < dis)
{
dis = cost[j].dis;
u = j;
}
}
vis[u] = true;
for (int v = 0; v < n; v++)
{
if (g[u][v] < inf)
{
if (cost[v].dis > dis + g[u][v])
{
cost[v].dis = dis + g[u][v];
cost[v].money = cost[u].money + p[u][v];
}
else if (cost[v].dis == dis + g[u][v])
cost[v].money = min(cost[v].money, cost[u].money + p[u][v]);
}
}
}
printf("%d %d\n", cost[t].dis, cost[t].money);
}
int main()
{
n = read(); m = read(); s = read(); t = read();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++) g[i][j] = inf;
cost[i].dis = cost[i].money = inf;
g[i][i] = 0;
}
while (m--)
{
int a = read(), b = read(), c = read(), d = read();
g[a][b] = g[b][a] = c;
p[a][b] = p[b][a] = d;
}
dijkstra(s, t);
return 0;
}
来源:CSDN
作者:SDUWH_2U
链接:https://blog.csdn.net/qq_35850147/article/details/103554338