07-图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
代码
我对dijkstra的逻辑重新理了一下,我认为我的判断更合理一些。即使已经收录的点,如果最短路径仍然相同,仍然需要判断一下它的cost,因为图里面我可以假设出两条完全相同的路从S->D,那么这两条路那一条被先收进去是按照顺序完全随机的,因此即使收了进去,如果路径相同,仍然要判断一下价格。
#include<iostream>
using namespace std;
#define MaxN 500
#define Inf 1000
#define Error -1
int dist[MaxN];
int cost[MaxN];
int collect[MaxN];
int path[MaxN];
typedef int Vertex;
typedef struct GraphNode* Graph;
struct GDataNode {
int dist;
int cost;
};
struct GraphNode{
int Nv;
GDataNode G[MaxN][MaxN];
};
void BuildGraph(Graph Gmap, int N_edge) {
auto Gdata = Gmap->G;
int S, D;
int Dist, Cost;
int Nv = Gmap->Nv;
for (int i = 0; i < Nv; i++) {
for (int j = 0; j < Nv; j++) {
Gdata[i][j].cost = Inf;
Gdata[i][j].dist = Inf;
}
}
for (int i = 0; i < N_edge; i++) {
cin >> S >> D >> Dist >> Cost;
Gdata[S][D].dist = Dist;
Gdata[S][D].cost = Cost;
Gdata[D][S].dist = Dist;
Gdata[D][S].cost = Cost;
}
}
Vertex FindMinDist(int Dist[], int Collect[], int N) {
Vertex V;
int MinDist = Inf;
for (int i = 0; i < N; i++) {
if (Collect[i] != 1 && Dist[i] < MinDist) {
MinDist = Dist[i];
V = i;
}
}
if (MinDist < Inf)
return V;
else
return Error;
}
void Dijkstra(Graph G, Vertex S, Vertex D) {
/*求G图中,S到D的最短路径长度,并输出相对应的花销,花销相同输出最小的*/
for (int i = 0; i < G->Nv; i++) {
dist[i] = Inf;
path[i] = -1;
cost[i] = Inf;
collect[i] = 0;
}
dist[S] = 0;
collect[S] = 1;
cost[S] = 0;
auto Gdata = G->G;
for (int i = 0; i < G->Nv; i++) {
if (Gdata[S][i].dist != Inf) {
dist[i] = Gdata[S][i].dist;
cost[i] = Gdata[S][i].cost;
path[i] = S;
}
}
Vertex V;
while (1) {
V = FindMinDist(dist, collect,G->Nv);
if (V == Error)break;
collect[V] = 1;
for (int W=0; W < G->Nv; W++) {
if ( Gdata[V][W].dist != Inf) {/*对V的邻接且未收录的点进行比较*/
if (collect[W] != 1 && dist[W] > dist[V] + Gdata[V][W].dist) {
dist[W] = dist[V] + Gdata[V][W].dist;
cost[W] = cost[V] + Gdata[V][W].cost;
path[W] = V;
}
if(dist[W] == dist[V] + Gdata[V][W].dist&&cost[W]>cost[V]+ Gdata[V][W].cost) {
cost[W] = cost[V] + Gdata[V][W].cost;
path[W] = V;
}
}
}
}
cout << dist[D] << " " << cost[D];
}
int main() {
int N, M, S, D;
cin >> N >> M>>S>>D;
Graph G = new GraphNode;
G->Nv = N;
BuildGraph(G, M);
Dijkstra(G, S, D);
return 0;
}