7-9 旅游规划 C语言

本文介绍了一个基于Dijkstra算法的程序,用于寻找从出发地到目的地的最短路径和最低费用。程序通过构建图并使用Dijkstra算法进行路径计算,适用于解决旅行路线规划问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

输入格式:

输入说明:输入数据的第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<stdlib.h>
#define MAXN 500 
#define INF 999999 

int N,M,S,D;//题目要求输入 
int dist[MAXN],cost[MAXN];

struct GNode{
	int lenth,cost;
}Graph[MAXN][MAXN];


void BuildGraph();
int Dijkstra();
int FindMin(int dist[],int collected[]);
 
int main(){
	BuildGraph();
	Dijkstra(); 
	printf("%d %d",dist[D],cost[D]);
	
	
}

void BuildGraph(){
	int i,j,n1,n2,c,l;
	scanf("%d%d%d%d",&N,&M,&S,&D);
	for(i = 0; i < N; i++){
		for(j = 0; j < N; j++){
			Graph[i][j].lenth = INF;
			Graph[i][j].cost = INF;
			if(i == j)
				Graph[i][j].lenth = 0;
				Graph[i][j].cost = 0;
		}
	}
	for(i = 0; i < M; i++){
		scanf("%d%d%d%d",&n1,&n2,&l,&c);
		Graph[n1][n2].cost = c;
		Graph[n1][n2].lenth = l;  
		Graph[n2][n1].cost = c;
		Graph[n2][n1].lenth = l;
	}
} 

int Dijkstra(){
	int i,collected[N];
	for(i = 0; i < N; i++){
		dist[i] = Graph[S][i].lenth;
		cost[i] = Graph[S][i].cost;
		collected[i] = 0;
	}
	dist[S] = 0;
	cost[S] = 0;
	collected[S] = 1;
	
	while(1){
		int v = FindMin(dist,collected);
		if(v == -1)
			break;
		collected[v] = 1;
		for(i = 0; i < N; i++){
			if(Graph[v][i].lenth < INF && collected[i] == 0){
				if(Graph[v][i].lenth < 0)
					return 0;
				if(dist[v] + Graph[v][i].lenth < dist[i]){
					dist[i] = dist[v] + Graph[v][i].lenth;
					cost[i] = cost[v] + Graph[v][i].cost;
				}else if(dist[v] + Graph[v][i].lenth == dist[i]){
					if(cost[v] + Graph[v][i].cost < cost[i]){
						cost[i] = cost[v] + Graph[v][i].cost;
					}
				}
				
			}
		}
	}
	return 1;
}

int FindMin(int dist[],int collected[]){
	int i,min,mindist = INF;
	for(i = 0; i < N; i++){
		if(collected[i] == 0 && dist[i] < mindist){//这里出问题,mindist和min分开来处理 
			min = i;
			mindist = dist[i];
		}
	}
	if(mindist < INF)
		return min;
	return -1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值