-
Notifications
You must be signed in to change notification settings - Fork 36
/
chapter9-weighted-shortest-path.cpp
93 lines (78 loc) · 1.56 KB
/
chapter9-weighted-shortest-path.cpp
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
91
92
93
// A simple illustration for weighted shortest path. Graph represented by adjacency matrix.
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int INFINITY = 1000000000;
void weightedShortestPath(const vector<vector<int> > &graph,
vector<int> &dist, vector<bool> &reachable)
{
// The minimal distances from 0th vertice to others.
int n;
int i, j;
n = (int)graph.size();
dist.resize(n);
reachable.resize(n);
if (n < 1) {
return;
}
for (i = 0; i < n; ++i) {
reachable[i] = false;
}
queue<int> q;
dist[0] = 0;
reachable[0] = true;
q.push(0);
while (!q.empty()) {
i = q.front();
q.pop();
for (j = 0; j < n; ++j) {
if (graph[i][j] == INFINITY || (reachable[j] &&
dist[i] + graph[i][j] >= dist[j])) {
continue;
}
dist[j] = dist[i] + graph[i][j];
if (!reachable[j]) {
q.push(j);
}
reachable[j] = true;
}
}
}
int main()
{
vector<vector<int> > graph;
vector<int> dist;
vector<bool> reachable;
int n;
int nk;
int i, j;
int tmp, tmp_dist;
while (cin >> n && n > 0) {
graph.resize(n);
for (i = 0; i < n; ++i) {
graph[i].resize(n, INFINITY);
}
for (i = 0; i < n; ++i) {
cin >> nk;
for (j = 0; j < nk; ++j) {
cin >> tmp >> tmp_dist;
graph[i][tmp] = tmp_dist;
}
}
weightedShortestPath(graph, dist, reachable);
for (i = 0; i < n; ++i) {
cout << i << ": ";
if (reachable[i]) {
cout << dist[i] << endl;
} else {
cout << "Unreachable" << endl;
}
}
for (i = 0; i < n; ++i) {
graph[i].clear();
}
graph.clear();
}
return 0;
}