这道题,就是改一改Dijastra算法,增加一个判断就好了,终于可以有半个小时能做好的题目了- -
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
//
// main.cpp
// Tour Plan
//
// Created by air on 2018/4/22.
// Copyright © 2018年 air. All rights reserved.
//
#define vertex int
#define Infinity 1<<20
#include <iostream>
using namespace std;
struct GNode{
vertex Nv;
vertex Ne;
int map[501][501];
int cost[501][501];
};
typedef GNode * ptrToNode;
typedef ptrToNode Graph;
Graph createGraph( int NofVertex, int Nofedge);
void Dijastra(Graph g, int begin, int end);
void test(int * a, int length);
void init(int* a, int begin, int Number);
void initToZero(int *a, int length);
int main(int argc, const char * argv[]) {
int Nofvertex; int Nofedge;
vertex begin; vertex end;
cin >> Nofvertex >> Nofedge >> begin >> end;
Graph g = new GNode;
g = createGraph(Nofvertex, Nofedge); // build a map of road and villages
Dijastra(g, begin ,end);
return 0;
}
void Dijastra(Graph g, int begin, int end){
int dist[g->Nv];
int cost[g->Nv];
int visit[g->Nv];
init(dist,begin,g->Nv);
init(cost,begin,g->Nv);
initToZero(visit,g->Nv);
// test(dist, g->Nv); 测一下测一下- -
// test(cost, g->Nv);
int min;
int N = g->Nv;
vertex V, W;
for(; ;){
min = Infinity;
for(int i = 0; i < N; i++)
if(!visit[i] && dist[i] < min){
min = dist[i];
V = i;
}
if(min == Infinity)
break;
visit[V] = 1;
for(W = 0; W < N; W ++){
if(! visit[W]){ //这个地方改一下就可以了
if(g->map[V][W] + dist[V] == dist[W]){
if(cost[V] + g->cost[V][W] < cost[W]){
cost[W] = cost[V] + g->cost[V][W];
}
}
if(g->map[V][W] + dist[V] < dist[W]){
dist[W] = dist[V] + g->map[V][W];
cost[W] = cost[V] + g->cost[V][W];
}
}
}
// test(dist, g->Nv);
// test(cost, g->Nv);
}
cout << dist[end] << " " << cost[end] << endl;
}
//init the distance , cost and visit arrays
void init(int* a, int begin, int Number){
for(int i = 0; i < Number; i++)
*(a + i) = Infinity;
*(a + begin) = 0;
}
void initToZero(int *a, int length){
for(int i = 0; i < length; i++)
*(a + i) = 0;
}
//build the graph
Graph createGraph( int NofVertex, int Nofedge){
Graph g = new GNode;
g->Nv = NofVertex;
g->Ne = Nofedge;
vertex i,j;
vertex V1, V2;
int length, cost;
for(i = 0; i < 501; i++){
for(j = 0; j < 501; j++){
g->map[i][j] = Infinity;
g->cost[i][j] = Infinity;
}
}
for( i = 0; i < Nofedge; i++){
cin >> V1 >> V2 >> length >> cost;
g->map[V1][V2] = length;
g->map[V2][V1] = length;
g->cost[V2][V1] = cost;
g->cost[V1][V2] = cost;
}
return g;
}
//自己检测用的额
void test(int * a, int length){
for(int i = 0; i < length; i ++)
cout << a[i] << " ";
cout << endl;
}