您的位置:首页 > 其它

hdoj2544 最短路

2012-08-21 17:08 246 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2544

Dijkstra算法应用

#include <iostream>
using namespace std;

const int intmax = 10000000;
const int MAX = 102;
int Map[MAX][MAX];
bool visited[MAX];
int dist[MAX];
int n, m;
void Dijsktra()
{
int i, j;
for (i = 1; i <= n; i++)
dist[i] = Map[1][i];
visited[1] = 1;
dist[1] = 0;
for (j = 1; j <= n; j++) {
int x = 1, m = intmax;
for (i = 1; i <= n; i++) //寻找最短路
if (!visited[i] && dist[i] < m)
m = dist[x=i];
visited[x] = 1;
for (i = 1; i <= n; i++)//更新
if (!visited[i] && Map[x][i] < intmax)
dist[i] = min(dist[i], dist[x]+Map[x][i]);
}
}
int main ()
{
int a, b, cost;
int i, j;
while (cin >> n >> m && (n+m)) {
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++) {
if (i == j) Map[i][j] = 0;
else Map[i][j] = intmax;
}
while (m--) {
cin >> a >> b >> cost;
if (cost < Map[a][b]) {//防止重路
Map[a][b] = cost;
Map[b][a] = cost;
}
}
memset (visited, 0, sizeof(visited));
for (i = 1; i <= n; i++)
dist[i] = intmax;
Dijsktra();//从1到各点的最短路径
cout << dist
<< endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: