07-图6-旅游规划-编程题

07-图6-旅游规划-编程题

解题代码

#include<stdio.h>
#include<stdlib.h>
#define MAXN 500
#define Infinite 65534
#define error -1
typedef struct Data Weight;
struct Data {
	int dist;
	int cost;
};
typedef struct GNode *PtrToGNode;
struct GNode {
	int Nv, Ne;
	Weight W[MAXN][MAXN];
};
typedef PtrToGNode MGraph;
int collection[MAXN], dist[MAXN], cost[MAXN];
MGraph BuildMGraph(int N, int M);
void Dijkstra(int S, MGraph G);
int FindMinDist(MGraph G);
int main()
{
	int N, M, S, D;
	scanf("%d %d %d %d", &N, &M, &S, &D);
	MGraph G = BuildMGraph(N,M);
	Dijkstra(S,G);
	printf("%d %d", dist[D], cost[D]);
	return 0;
}
MGraph BuildMGraph(int N,int M) {
	MGraph G = (MGraph)malloc(sizeof(struct GNode));
	G->Nv = N;
	G->Ne = M;
	for(int i=0;i<N;i++)
		for (int j = 0; j < N; j++) 
			G->W[i][j].dist = G->W[i][j].cost = Infinite;
	int temp_dist, temp_cost, temp_s, temp_d;
	for (int i = 0; i < M; i++) {
		scanf("%d %d %d %d", &temp_s, &temp_d, &temp_dist, &temp_cost);
		G->W[temp_s][temp_d].cost = G->W[temp_d][temp_s].cost = temp_cost;
		G->W[temp_s][temp_d].dist = G->W[temp_d][temp_s].dist = temp_dist;
	}
	for (int i = 0; i < G->Nv; i++) {
		dist[i] = cost[i] = Infinite;
		G->W[i][i].cost = G->W[i][i].dist = 0;
	}
	return G;
}
void Dijkstra(int S,MGraph G) {
	int v;
	for (int i = 0; i < G->Nv; i++) {
		dist[i] = G->W[S][i].dist;
		cost[i] = G->W[S][i].cost;
	}
	collection[S] = 1;
	while (1) {
		v = FindMinDist(G);
		if (v == error) break;
		collection[v] = 1;
		for (int i = 0; i < G->Nv; i++) {
			if (!collection[i] && dist[v] + G->W[v][i].dist < dist[i]) {
				dist[i] = dist[v] + G->W[v][i].dist;
				cost[i] = cost[v] + G->W[v][i].cost;
			}
			else if (!collection[i] && dist[v] + G->W[v][i].dist == dist[i] && cost[v] + G->W[v][i].cost < cost[i]) 
				cost[i] = cost[v] + G->W[v][i].cost;
		}
	}
}
int FindMinDist(MGraph G) {
	int mindist=Infinite, minv=0;
	for (int i = 0; i < G->Nv; i++) {
		if (!collection[i] && dist[i] < mindist) {
			mindist = dist[i];
			minv = i;
		}
	}
	if (mindist < Infinite) return minv;
	return error;
}

测试结果

在这里插入图片描述

问题整理

1.Dijkstra算法对我不友好,需要多加练习。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值