PAT A1030 Travel Plan(30 分)
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
链接:
https://pintia.cn/problem-sets/994805342720868352/problems/994805464397627392
代码:
#include <fstream>
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 510;
#define INF 0x3f3f3f3f
int n, m, s, e;
struct Graph{
int dist, cost;
}G[maxn][maxn];
int d[maxn], w[maxn], pre[maxn];
bool vis[maxn];
void Dijkstra(){
fill(d, d + maxn, INF);
fill(w, w + maxn, INF);
d[s] = 0;
w[s] = 0;
for(int i = 0; i < n; ++i){
int u = -1, minV = INF;
for(int i = 0; i < n; ++i){
// if(!vis[i] && minV > G[s][i].dist){
if(!vis[i] && minV > d[i]){
minV = d[i];
u = i;
}
}
vis[u] = true;
for(int i = 0; i < n; ++i){
if(!vis[i] && G[u][i].dist != INF){
if(d[i] > d[u] + G[u][i].dist){
d[i] = d[u] + G[u][i].dist;
w[i] = w[u] + G[u][i].cost;
pre[i] = u;
}
else if(d[i] == d[u] + G[u][i].dist && w[i] > w[u] + G[u][i].cost){
w[i] = w[u] + G[u][i].cost;
pre[i] = u;
}
}
}
}
}
void dfs(int u){
if(u == s) return ;
dfs(pre[u]);
printf(" %d", u);
}
int main(){
// freopen("a.txt", "r", stdin);
int c1, c2, c3, c4;
scanf("%d%d%d%d", &n, &m, &s, &e);
for(int i = 0; i < n; ++i){ //
for(int j = 0; j < n; ++j){
G[i][j].dist = G[i][j].cost = INF;
}
}
for(int i = 0; i < m; ++i){
scanf("%d%d%d%d", &c1, &c2, &c3, &c4);
G[c1][c2].dist = G[c2][c1].dist = c3;
G[c1][c2].cost = G[c2][c1].cost = c4;
}
memset(vis, 0, sizeof(vis));
Dijkstra();
printf("%d", s);
dfs(e);
printf(" %d %d\n", d[e], w[e]);
return 0;
}

本文介绍了一种解决旅行者地图上从起点到终点最短路径问题的算法,考虑到距离和成本,当最短路径不唯一时,选择总成本最低的路径。输入包括城市数量、高速公路数量、起点和终点,以及每条高速公路的距离和成本。
2167

被折叠的 条评论
为什么被折叠?



