dijkstra模板

模板一:

const int maxn = 10001;
void Dijkstra(int n, int dist[maxn], int map[maxn][maxn], int pre[maxn], int s)
{
	int i, j, k;
	int min;
	bool p[maxn];
	for (i = 1; i <= n; i++)
	{
		p[i] = false;
		if (i != s)
		{
			dist[i] = map[s][i];
			pre[i] = s;
		}
	}
	dist[s] = 0;
	p[s] = true;
	for (i = 1; i <= n - 1; i++)
	{
		min = INT_MAX;
		k = 0;
		for (j = 1; j <= n; j++)
		{
			if (!p[j] && dist[j] < min)
			{
				min = dist[j];
				k = j;
			}
		}
	}
	if (k == 0) return;
	p[k] = true;
	for (j = 1; j <= n; j++)
	{
		if (!p[j] && map[k][j] != INT_MAX && dist[j] > dist[k] + map[k][j])
		{
			dist[j] = dist[k] + map[k][j];
			pre[j] = k;
		}
	}
}


模板二:

#include<iostream>
#define max 50
#define INF 0x7fffffff
using namespace std;
int matrix[max][max];
void Dijkstra(int out[], int N, int V0)
{
	int i;
	int visited[max] = { 0 };
	int last_visited = 0;
	for (i = 0; i < N; i++)
	{
		out[i] = INF;
	}
	visited[V0] = 1;
	out[V0] = 0;

	for (i = 0; i < N - 1; i++)
	{
		for (int j = 0; j < N; j++)
		{
			if (visited[j] == 0)
			{
				if (matrix[V0][j] != 0)
				{
					int dis = matrix[V0][j] + last_visited;
					if (dis < out[j])
					{
						out[j] = dis;
					}
				}
			}
		}
		int minIdex = 0;
		while (visited[minIdex] == 1)
			minIdex++;
		for (int j = minIdex; j < N; j++)
		{
			if (visited[j] == 0 && out[j] < out[minIdex])
			{
				minIdex = j;
			}
		}

		visited[minIdex] = 1;
		last_visited = out[minIdex];
		V0 = minIdex;

	}



}
int main()
{
	int n;

	int result[max];
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			cin >> matrix[i][j];
		}
	}
	Dijkstra(result,n,0);
	for (int i = 0; i < n; i++)
	{
		if (result[i] == INF)
			cout << "INF"<<" ";
		else
		cout << result[i] << " ";
	}
	system("pause");
}
/*8
0 20 0 80 0 0 90 0
0 0 0 0 0 10 0 0
0 0 0 10 0 50 0 20
0 0 10 0 0 0 20 0
0 50 0 0 0 0 30 0
0 0 10 40 0 0 0 0
20 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0*/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值