1030. Travel Plan

#include <stdio.h>
#include <stdlib.h>
#define MaxVNum 500
#define INFINITY 100000

typedef int Vertex;
typedef struct MGraph {
	int Distance[MaxVNum][MaxVNum];
	int Cost[MaxVNum][MaxVNum];
	int VertexNum;
}MGraph,*PMGraph;

void Dijkstra(PMGraph PGraph, int dist[], int cost[], int path[], Vertex S);
Vertex MinDist(PMGraph PGraph,int collected[], int dist[]);
void PrintPath(int path[], Vertex D);

int main()
{
	PMGraph PGraph=(PMGraph)malloc(sizeof(MGraph));
	int M, i,j,distance,c;
	Vertex S, D, c1, c2;
	scanf("%d %d %d %d", &PGraph->VertexNum, &M, &S, &D);
	int *dist = (int*)malloc(sizeof(int)*PGraph->VertexNum);
	int *cost = (int*)malloc(sizeof(int)*PGraph->VertexNum);
	int *path = (int*)malloc(sizeof(int)*PGraph->VertexNum);
	
	for (i = 0; i < PGraph->VertexNum; i++)
		for (j = 0; j < PGraph->VertexNum; j++) {
			PGraph->Distance[i][j] = INFINITY;
			PGraph->Cost[i][j] = INFINITY;
	}

	for (i = 0; i < M; i++) {
		scanf("%d %d %d %d", &c1, &c2, &distance, &c);
		PGraph->Distance[c1][c2] = distance;
		PGraph->Distance[c2][c1] = distance;
		PGraph->Cost[c1][c2] = c;
		PGraph->Cost[c2][c1] = c;
	}
	Dijkstra(PGraph, dist, cost, path, S);
	printf("%d ", S);
	PrintPath(path, D);
	printf("%d %d",dist[D],cost[D]);
	return 0;
}

void Dijkstra(PMGraph PGraph, int dist[],int cost[], int path[], Vertex S)
{
	Vertex v,w;
	int *collected = (int*)malloc(sizeof(int)*PGraph->VertexNum);
	for (v = 0; v < PGraph->VertexNum; v++) {
		collected[v] = 0;
		dist[v] = PGraph->Distance[S][v];
		cost[v] = PGraph->Cost[S][v];
		path[v] = -1;
	}
	dist[S] = 0;
	collected[S] = 1;
	cost[S] = 0;
	while (1) {
		v = MinDist(PGraph,collected, dist);
		if (v == -1)
			break;
		collected[v] = 1;
		for (w = 0; w < PGraph->VertexNum; w++)
			if ((!collected[w]) && (PGraph->Distance[v][w] < INFINITY))
				if (dist[v] + PGraph->Distance[v][w] < dist[w]) {
					dist[w] = dist[v] + PGraph->Distance[v][w];
					cost[w] = cost[v] + PGraph->Cost[v][w];
					path[w] = v;
				}
				else if (dist[v] + PGraph->Distance[v][w] == dist[w] && cost[v] + PGraph->Cost[v][w] < cost[w]) {
					cost[w] = cost[v] + PGraph->Cost[v][w];
					path[w] = v;
				}
	}
}

Vertex MinDist(PMGraph PGraph, int collected[], int dist[])
{
	Vertex MinV, V;
	int MinDist = INFINITY;

	for (V = 0; V<PGraph->VertexNum; V++) {
		if (!collected[V] && dist[V]<MinDist) {
			MinDist = dist[V]; 
			MinV = V; 
		}
	}
	if (MinDist < INFINITY) 
		return MinV; 
	else return -1;  
}

void PrintPath(int path[], Vertex D)
{
	Vertex v=D;
	if(path[v] != -1)
		PrintPath(path, path[v]);
	printf("%d ",v);
}

两个权值的Dijkstra问题。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值