7-图6 旅游规划 (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
Note
- 改进的dijkstra,当纳入新点使得集合外一点到源点长度变短,或新路径长度与原路径长度相等 && 费用变少 则该点在源点到集合外那点的最短路上。
- 注意初始化
#include<iostream>
using namespace std;
#define MAX 500
int main() {
int cost[MAX], dist[MAX] = {MAX} , c[MAX][MAX], a[MAX][MAX];
int num, arc, start, destination;
int collected[MAX] = {0};
int path[MAX] = {-1};
cin >> num >> arc >> start >> destination;
for(int i = 0; i < num; i++){ //初始化
for(int j =0; j < num; j++){
a[i][j] = c[i][j] = MAX;
}
}
for(int i = 0; i < arc; i++){ //输入
int aa, b, tempa, tempb;
cin >> aa >> b >> tempa >> tempb;
a[aa][b] = a[b][aa] = tempa;
c[aa][b] = c[b][aa] = tempb;
}
for(int i = 0; i < num; i++){ //初始化
if(i != start){
dist[i] = a[start][i];
cost[i] = c[start][i];
if(dis[i] < MAX){
path[i] = start;
}
}
}
collected[start] = 1;
while(1){
int min = MAX, ptr;
for(int i = 0; i < num; i++){ //找临边中最小的
if(!collected[i] && dist[i] < min){
min = dist[i];
ptr = i;
}
}
if(min == MAX){ //无法更新,退出
break;
}
collected[ptr] = 1;
for(int i = 0; i < num; i++) { //如果收录ptr使start到i的距离变短,则start到i的最短路一定经过ptr
if(!collected[i] && dist[ptr] + a[ptr][i] < dist[i] ){
dist[i] = dist[ptr] + a[ptr][i];
path[i] = ptr;
cost[i] = cost[ptr] + c[ptr][i]; // ?
}
else if(!collected[i] && dist[ptr] + a[ptr][i] == dist[i] && cost[ptr] + c[ptr][i] < cost[i]){
cost[i] = cost[ptr] + c[ptr][i];
path[i] = ptr;
}
}
}
cout << dist[destination] << " " << cost[destination];
return 0;
}
Summary
- 初始化的时候 dist[start的临界点] = 边的长度, visited[start] = 1, path[start的临界点] = start(dist[start]貌似不初始化也可以)
- Dijkstra的本质就是如果收录v使得s到w的距离变短,则s到w的最短路一定经过v
类似问题
要求算出最短路径有多少条
解:
- 设count数组计算最短路条数,初始化与s有临边的v count[v] = 1;
- 如果把节点v纳入集合,使得start到w(v的临边)的距离变短 则 count[w] = count[v]
- 如果把节点v纳入集合,使得过节点v到w的距离等于原集合到w的距离distance 则 count[w] += cout[v]
例子:
A1003
要求边数最少的最短路(注: 先保证最短,再保证边数最少)
- 设count数组计算走过的边数,初始化与s有临边的v count[v] = 1;
- 如果把节点v纳入集合,使得start到w(v的临边)的距离变短 则 count[w] = count[v] + 1
- 如果把节点v纳入集合,使得过节点v到w的距离等于原集合到w的距离distance 并且count[w] > cout[v] + 1 则 count[w] > cout[v] + 1