25.单源最短路径 Dijkstra


#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<queue>
#include<stack>
#define OK 0
#define ERROR 1
#define MAXSIZE 1000
using namespace std;
typedef int ElemType;
FILE *fp;
void InitFile()
{
	bool e;
	fopen_s(&fp, "data.txt", "r");
	if (!fp) exit(ERROR);
	return;
}
typedef bool Status;


 单源最短路径 Dijkstra
/******
file input:


*******/



/*typedef struct node
{
int vertex;
struct node *link;

}Node, *node_ptr;*/

//node_ptr vertex;

#define MAX_VERTICES 6
#define MAX_VALUE 1000

int mydistance[MAX_VERTICES];
int found[MAX_VERTICES];
int cost[][MAX_VERTICES] =
{
	0, 50, 10, MAX_VALUE, 45, MAX_VALUE,
	MAX_VALUE, 0, 15, MAX_VALUE, 10, MAX_VALUE,
	20, MAX_VALUE, 0, 15, MAX_VALUE, MAX_VALUE,
	MAX_VALUE, 20, MAX_VALUE, 0, 35, MAX_VALUE,
	MAX_VALUE, MAX_VALUE, 30, MAX_VALUE, 0, MAX_VALUE,
	MAX_VALUE, MAX_VALUE, MAX_VALUE, 3, MAX_VALUE, 0
};
;


int choose(int mydistance[], int n, int found[])//选择最小代价的边
{
	int i, min, minpos;
	min = MAX_VALUE;
	minpos = -1;
	for (i = 0; i < MAX_VERTICES; i++)
	{
		if (mydistance[i] < min && !found[i])
		{
			min = mydistance[i];
			minpos = i;
		}
	}
	return minpos;
}

//单源最短路径
void shorteatpath(int v, int cost[][MAX_VERTICES], int mydistance[], int n, int found[])
{
	int i, u, w;
	for (i = 0; i < MAX_VERTICES; i++){ found[i] = 0; mydistance[i] = cost[v][i]; }
	found[v] = 1;
	mydistance[v] = 0;
	for (i = 0; i < n-1; i++)//  i<n-2 为什么 
	{
		u = choose(mydistance, n, found);
		if (u < 0) continue;/
		found[u] = 1;
		for (w = 0; w < n; w++)
		{
			if (!found[w])
			if (mydistance[u] + cost[u][w] < mydistance[w])
				mydistance[w] = mydistance[u] + cost[u][w];
		}

	}
}


//by zhaoyang   @  2014.4.20
int main()
{
	//InitFile();;



	for (int j = 0; j < MAX_VERTICES; j++)
	{
		printf("%d:\t", j);
		//for (int i = 0; i < MAX_VERTICES; i++)  found[i] = 0;
		shorteatpath(j, cost, mydistance, MAX_VERTICES, found);
		for (int i = 0; i < MAX_VERTICES; i++)
		if (mydistance[i] != MAX_VALUE)
			printf("%d %d\t", i, mydistance[i]);
		else printf("%d   \t", i);
		printf("\n");

	}
	//fclose(fp);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值