A1030 Travel Plan (30 point(s))

Dijskstra 求最短路径,最少花费

1. 原文

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:

1
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:

1
2
3
4
5
6
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:

1
0 2 3 3 40

2. 解析

最短路径,最少花费

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=510;
const int Inf=312312312;
int graph[maxn][maxn];
int cost[maxn][maxn];
bool visit[maxn]={false};
int dis[maxn];
int co[maxn];
int pre[maxn]={};
int s;
vector<int> path;
void dfs(int t){
if (s==t)
{
printf("%d ",s);
return;
}else{
dfs(pre[t]);
}
printf("%d ",t);
}
int main()
{
fill(graph[0],graph[0]+maxn*maxn,Inf);
int n,m,d;
scanf("%d%d%d%d",&n,&m,&s,&d);
int a,b;
for (int i = 0; i < m; ++i)
{
scanf("%d%d",&a,&b);
scanf("%d%d",&graph[a][b],&cost[a][b]);
graph[b][a]=graph[a][b];
cost[b][a]=cost[a][b];
}
fill(dis,dis+maxn,Inf);
fill(co,co+maxn,Inf);
dis[s]=0;
co[s]=0;
for (int i = 0; i < n; ++i)
{
int u=-1; int min=Inf;
for (int j = 0; j < n; ++j)
{
if (visit[j]==false&&min>dis[j])
{
min=dis[j];
u=j;
}
}
if (u==-1)
{
break;
}
visit[u]=true;
for (int v = 0; v < n; ++v)
{
if (visit[v]==false&&graph[u][v]!=Inf)
{
if (dis[u]+graph[u][v]<dis[v])
{
dis[v]=dis[u]+graph[u][v];
co[v]=co[u]+cost[u][v];
pre[v]=u;
}else if(dis[u]+graph[u][v]==dis[v]){
if (co[u]+cost[u][v]<co[v])
{
co[v]=co[u]+cost[u][v];
pre[v]=u;
}
}
}
}
}
dfs(d);
printf("%d %d\n",dis[d],co[d]);
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1030/
  • 发布时间: 2019-09-03 12:35
  • 更新时间: 2021-10-29 14:00
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!