7-9-旅游规划-编程题

7-9-旅游规划-编程题

  • 解题代码
  • 测试结果
  • 问题整理

解题代码

#include
#define MAXN 500
#define Infinite 65534
#define ERROR -1
typedef struct WNode Weight;
struct WNode {
	int dist;
	int cost;
}G[MAXN][MAXN];
int dist[MAXN], cost[MAXN], visit[MAXN];
int N, M, S, D;
void Inicialization(void);
void Dijkstra(void);
int FindMinDist(void);
int main()
{
	scanf("%d %d %d %d", &N, &M, &S, &D);
	Inicialization();
	Dijkstra();
	printf("%d %d", dist[D], cost[D]);
	return 0;
}
void Inicialization(void) {
	for (int i = 0; i < N; i++)
		for (int j = 0; j < N; j++)
			G[i][j].cost = G[i][j].dist = Infinite;
	int v1, v2, td, tc;
	for (int i = 0; i < M; i++) {
		scanf("%d %d %d %d", &v1, &v2, &td, &tc);
		G[v1][v2].cost = G[v2][v1].cost = tc;
		G[v1][v2].dist = G[v2][v1].dist = td;
	}
	for (int i = 0; i < N; i++) 
		dist[i] = cost[i] = Infinite;
}
void Dijkstra(void) {
	dist[S] = 0;
	cost[S] = 0;
	int V;
	while (1) {
		V = FindMinDist();
		if (V == ERROR) break;
		visit[V] = 1;
		for (int i = 0; i < N; i++)
			if (!visit[i] && G[i][V].dist < Infinite ) 
				if(dist[V] + G[V][i].dist < dist[i] || (dist[V] + G[V][i].dist == dist[i] && cost[V] + G[V][i].cost < cost[i])) {
				dist[i] = dist[V] + G[V][i].dist;
				cost[i] = cost[V] + G[V][i].cost;
			}
	}
}
int FindMinDist(void) {
	int min = Infinite, index;
	for (int i = 0; i < N; i++)
		if (!visit[i] && dist[i] < min) {
			index = i;
			min = dist[i];
		}
	if (min == Infinite) return ERROR;
	return index;
}

测试结果

7-9-旅游规划-编程题_第1张图片

问题整理

1.Dijkstra,也慢慢会写了,注意一下findmindist的返回值,别返回min,而是index。

你可能感兴趣的:(7-9-旅游规划-编程题)