HDU - 2544 最短路 (Dijkstra)

解析:Dijkstra算法的入门题。

如果对Dijkstra算法不理解的请看:http://www.it165.net/pro/html/201407/16957.html

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 105;
int w[N][N],d[N],vis[N];
int n,m;
void init() {
	for(int i = 0; i <= n; i++) {
		for(int j = 0; j <= n; j++) {
			if(i == j) {
				w[i][j] = 0;
			}else {
				w[i][j] = INF;
			}
		}
	}
}
void dijkstra(int s) {
	memset(vis,0,sizeof(vis));
	for(int i = 1; i <= n; i++) {
		d[i] = INF;
	}
	d[s] = 0;
	int x,mind;
	for(int i = 1; i <= n; i++) {
		mind = INF;
		for(int y = 1; y <= n; y++) {
			if(!vis[y] && d[y] <= mind) {
				x = y;
				mind = d[x];
			}
		}
		vis[x] = true;
		for(int y = 1; y <= n; y++) {
			d[y] = min(d[y],d[x]+w[x][y]);
		}
	}
}
int main() {
	int u,v,val;
	while(scanf("%d%d",&n,&m) != EOF && (n || m)) {
		init();
		for(int i = 0; i < m; i++) {
			scanf("%d%d%d",&u,&v,&val);
			w[u][v] = val;
			w[v][u] = val;
		}
		dijkstra(1);
		printf("%d\n",d[n]);
	}
	return 0;
}


你可能感兴趣的:(最短路,HDU,2544)