HDU 2544 最短路 (SSSP & O(V^2)的Dijkstra算法)

http://acm.hdu.edu.cn/showproblem.php?pid=2544


模板题。


完整代码:

/*15ms,276KB*/

#include<cstdio>
#include<cstring>
const int mx = 101;

int n, m, dis[mx][mx], disTo[mx];
bool vis[mx];

void dij(int st)
{
	int i, j, pos;
	memcpy(disTo, dis[st], sizeof(disTo));
	memset(vis, 0, sizeof(vis));
	disTo[st] = 0, vis[st] = true;
	for (i = 1; i <= n; ++i)
	{
		int min = 0x3f3f3f3f;
		for (j = 1; j <= n; ++j)
			if (!vis[j] && disTo[j] < min)
				min = disTo[j], pos = j;
		vis[pos] = true;
		for (j = 1; j <= n; ++j)
			if (!vis[j] && disTo[pos] + dis[pos][j] < disTo[j])
				disTo[j] = disTo[pos] + dis[pos][j];
	}
}

int main()
{
	int i, st, ed, len;
	while (scanf("%d%d", &n, &m), n)
	{
		memset(dis, 0x3f, sizeof(dis));
		for (i = 1; i <= m; ++i)
		{
			scanf("%d%d%d", &st, &ed, &len);
			if (dis[st][ed] > len)
				dis[st][ed] = dis[ed][st] = len;
		}
		dij(1);
		printf("%d\n", disTo[n]);
	}
	return 0;
}

你可能感兴趣的:(C++,ACM,HDU,dijkstra)