07-图6 旅游规划   (25分)

来源:互联网 发布:淘宝个人简历模板 编辑:程序博客网 时间:2024/05/16 00:36

有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。

输入格式:

输入说明:输入数据的第1行给出4个正整数NMSD,其中N2N500)是城市的个数,顺便假设城市的编号为0~(N-1);M是高速公路的条数;S是出发地的城市编号;D是目的地的城市编号。随后的M行中,每行给出一条高速公路的信息,分别是:城市1、城市2、高速公路长度、收费额,中间用空格分开,数字均为整数且不超过500。输入保证解的存在。

输出格式:

在一行里输出路径的长度和收费总额,数字间以空格分隔,输出结尾不能有多余空格。

输入样例:

4 5 0 30 1 1 201 3 2 300 3 4 100 2 2 202 3 1 20

输出样例:

3 40


解析:Dijkstra算法增加一个totalprice,去掉path

#include <stdio.h>#include <stdlib.h>#define MAX 505#define INFINITY 100000struct node{int length, price;//length的值代表了图中的边及权重,用INFINITY代表不存在}city[MAX][MAX];int N, M, S, D;int dist[MAX], path[MAX], totalprice[MAX];void Dijkstra(int s){int collected[MAX];int v, w;//初始化for(v = 0; v < N; v++){dist[v] = city[v][s].length;totalprice[v] = city[v][s].price;////此题不需要path//if( dist[v] < INFINITY )//path[v] = s;//else//path[v] = -1;collected[v] = 0;}//先将起点收入集合dist[s] = 0;totalprice[s] = 0;collected[s] = 1;while(1){//找到未收录顶点中dist的最小者int MinDist = INFINITY, MinV;for( v = 0; v < N; v++)if( collected[v] == 0 && dist[v] < MinDist ){MinDist = dist[v];MinV = v;}//如果找不到最小未收录的顶点,则退出函数if( MinDist == INFINITY )return ;v = MinV;collected[v] = 1;//收录vfor(w = 0; w < N; w++){  //对于图中每个顶点w//若w是v的邻接点且未被收录if( collected[w] == 0 && city[v][w].length < INFINITY ) {//如果收录v使得dist[w]变小if( dist[v] + city[v][w].length < dist[w] ) {dist[w] = dist[v] + city[v][w].length;totalprice[w] = totalprice[v] + city[v][w].price;//经过w所花的钱 = 经过v花的钱 + v到w花的钱//path[w] = v;}//如果收录v并不影响dist[w],但是总价变少else if( dist[v] + city[v][w].length == dist[w] && totalprice[v] + city[v][w].price < totalprice[w] ) {dist[w] = dist[v] + city[v][w].length;totalprice[w] = totalprice[v] + city[v][w].price;//path[w] = v;}}}}}int main(){int a, b;scanf("%d%d%d%d", &N, &M, &S, &D);//INFINITY代表两点间没有边for(int i = 0; i < N; i++)for(int j = 0; j < N; j++)city[i][j].length = INFINITY;for(int i = 0; i < M; i++){scanf("%d%d", &a, &b);scanf("%d%d", &city[a][b].length, &city[a][b].price);city[b][a] = city[a][b];}Dijkstra(S);printf("%d %d", dist[D], totalprice[D]);system("pause");return 0;}


0 0
原创粉丝点击