标签:
简单的最短路径题
题目页:http://acm.hdu.edu.cn/showproblem.php?pid=2544
没什么好说的,可以用单源最短路径的各种算法解题,所有节点对的最短路径…………解题,这里用 dijkstra 算法。练习一下 dijkstra 算法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
#include <iostream> #define Infinite 10000000 int number_points, number_ways; int buffer_consume[110][110]; int dist[110]; bool discovered[110]; // return: 返回未发现顶点的最短路径的下标 // remark: 遍历搜寻未发现顶点的最短路径的下标, // 预计耗时 O(v) int getMinIndex() { int min_value = Infinite; int min_index = 0; for ( int i = 1; i <= number_points; i++) { if (discovered[i] == false && dist[i] <= min_value) { min_value = dist[i]; min_index = i; } } return min_index; }; void dijkstra() { for ( int i = 1; i <= number_points; i++) { dist[i] = buffer_consume[1][i]; discovered[i] = false ; } dist[1] = 0; discovered[1] = true ; for ( int count = 1; count != number_points; count++) { int u = getMinIndex(); // 获取未发现顶点的最短路径的下标 discovered[u] = true ; // 标记为已发现 if (u == number_points) // 目标顶点已被发现,算法终止。 return ; // for each (u, v) 松弛操作 for ( int v = 1; v <= number_points; v++) { if (dist[u] + buffer_consume[u][v] < dist[v]) dist[v] = dist[u] + buffer_consume[u][v]; } } } int main() { // 读取第一组数据的两行 scanf ( "%d%d" , &number_points, &number_ways); while (number_points != 0 && number_ways != 0) { // 1. 初始化 for ( int x = 1; x <= number_points; x++) for ( int y = 1; y <= number_points; y++) { buffer_consume[x][y] = Infinite; } // 2. 读取路径 for ( int i = 0; i < number_ways; i++) { int x, y, consume; scanf ( "%d%d%d" , &x, &y, &consume); buffer_consume[x][y] = consume; buffer_consume[y][x] = consume; } // 3. dijkstra 算法 dijkstra(); // 4. 输出答案 printf ( "%d\n" , dist[number_points]); // 5. 读取下一组数据 scanf ( "%d%d" , &number_points, &number_ways); } return 0; } |
标签:
原文地址:http://www.cnblogs.com/night-ride-depart/p/5080374.html