HDU_2544 最短路(Dijkstra)

很裸的最短路径问题,这里用Dijkstra做的,前边已经写过Floyd和SPFA算法

SPFA:http://www.cnblogs.com/vongang/archive/2011/08/16/2141334.html

Floyd:http://www.cnblogs.com/vongang/archive/2011/08/16/2141019.html


My Code:

#include <iostream>
#include
<cstring>
#include
<cstdio>
using namespace std;

const int maxnum = 107;
const int inf = 999999;

int dist[maxnum];
int map[maxnum][maxnum];
int vis[maxnum];
int n, m;

void Dijkstra()
{
int i, j;
memset(vis,
0, sizeof(vis));
for(i = 1; i <= n; i++)
{
dist[i]
= map[1][i];
vis[i]
= 0;
}
dist[
1] = 0;
vis[
1] = 1;
for(i = 2; i <= n; i++)
{
int flag, min = inf;
for(j = 1; j <= n; j++)
if(!vis[j] && dist[j] < min)
{
flag
= j;
min
= dist[j];
}
vis[flag]
= 1;
for(j = 1; j <= n; j++)
if(!vis[j] && map[flag][j] < inf)
{
int newdist = dist[flag] + map[flag][j];
if(newdist < dist[j])
dist[j]
= newdist;
}
}
}
int main()
{
//freopen("data.in", "r", stdin);
int i, j, a, b, c;
while(scanf("%d%d", &n, &m), n||m)
{
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
map[i][j]
= inf;
while(m--)
{
scanf(
"%d%d%d", &a, &b, &c);
if(c < map[a][b])
map[a][b]
= map[b][a] = c;
}
Dijkstra();
printf(
"%d\n", dist[n]);
}
return 0;
}
posted @ 2011-08-16 19:35  AC_Von  阅读(295)  评论(0编辑  收藏  举报