PTA 旅游规划 C语言 最短路径--Dijkstra

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

输入格式:
输入说明:输入数据的第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
#include<stdio.h>
#include<string.h>
#define MaxSize 550
typedef struct {
	int w, cost;
} Graph;
Graph route[MaxSize][MaxSize];
int N, M, S, D;
int final[MaxSize], dist[MaxSize], path[MaxSize], cost[MaxSize];
int	figure = 1;
//head[u]为编号为u的结点的孩子头,count[u]为编号为u有几个孩子
//完成作用:在编号为u的结点的孩子头部插入v结点

void CreateGraph(int i) {//无向图
	while (i--) {
		int u, v, w, cost;
		scanf("%d%d%d%d", &u, &v, &w, &cost);
		route[u][v].w = w;
		route[u][v].cost = cost;
		route[v][u].w = w;
		route[v][u].cost = cost;
	}
}
void Dijkstra(int u, int v) {
	for (int i = 0; i <= N; i++) {
		if (route[u][i].w == -1||i==u)
			continue;
		if (final[i] != 1) {
			if (dist[i] > dist[u] + route[u][i].w || u == S) {
				if (u == S) {
					dist[i] = route[u][i].w;
					cost[i] = route[u][i].cost;
					path[i] = S;
				}
				//printf("dist[k]:%d 新的dist[k]:%d\n", dist[edge[i].to], dist[u] + edge[i].w);
				else {
					dist[i] = dist[u] + route[u][i].w;
					cost[i] = cost[u] + route[u][i].cost;
					path[i] = u;
				}
			}
			if (dist[i] == dist[u] + route[u][i].w && cost[i] > cost[u] + route[u][i].cost) {
				cost[i] = cost[u] + route[u][i].cost;
				path[i] = u;
			}
		}
	}
	int min = 0x3f3f3f, temp;
	for (int i = 0; i < N; i++) {
		if (final[i] != 1 && min > dist[i] ) {
			min = dist[i];
			temp = i;
		}
	}
	final[temp] = 1;
	figure++;
	if (figure != N)
		Dijkstra(temp, v);
	return ;
}

int main() {
	memset(route, -1, sizeof(Graph)*MaxSize*MaxSize);
	scanf("%d%d%d%d", &N, &M, &S, &D);
	CreateGraph(M);
	memset(final, 0, sizeof(int)*MaxSize);//代表dist[k]是已经为最短
	memset(dist, 600, sizeof(int)*MaxSize);//代表从u到k的路径长度
	memset(path, -1, sizeof(int)*MaxSize);//储存前驱
	memset(cost, 600, sizeof(int)*MaxSize);//代表从u到k的车费
	final[S] = 1;
	Dijkstra(S, D);
	printf("%d %d", dist[D], cost[D]);
}

在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

快苏排序OAO

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值