您的位置:首页 > Web前端 > JavaScript

[hiho 23]单源最短路-Dijstra算法

2015-05-31 23:34 686 查看
题目描述

维护一个集合,集合中的元素与点u的最短距离已经确定,求出集合内元素所能到达的点到点u的距离,取最短的距离对应的点加入集合直到集合包含点v。

每次更新距离只与新加入集合的点有关。

#include <stdio.h>
#include <string.h>
#include <algorithm>

#define N 1005

unsigned w

;

int main(){
memset(w, -1, sizeof(w));
int n, m, u, v;
scanf("%d%d%d%d", &n, &m, &u, &v);
int from, to;
unsigned weight;
for (int i = 0; i < m; i++) {
scanf("%d%d%u", &from, &to, &weight);
weight = std::min(weight, w[from][to]);
w[from][to] = w[to][from] = weight;
}
int min_idx;
unsigned min;
while (true) {
min_idx = 1;
min = w[u][1];
for (int i = 2; i <= n; i++) {
if (min > w[u][i]) {
min = w[u][i];
min_idx = i;
}
}
for (int i = 1; i <= n; i++) {
if (w[min_idx][i] != (unsigned)-1) {
w[u][i] = std::min(w[u][i], w[u][min_idx] + w[min_idx][i]);
}
}
if (min_idx == v) {
break;
} else {
w[u][min_idx] = -1;
}
}
printf("%u\n", w[u][v]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: