-
Notifications
You must be signed in to change notification settings - Fork 0
/
MilesToChicago.cpp
74 lines (63 loc) · 1.81 KB
/
MilesToChicago.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
/* https://www.urionlinejudge.com.br/judge/en/problems/view/1655
#bellman-ford #shortest-path
*/
#include<iostream>
#include<vector>
#include<cfloat>
#include<iomanip>
using namespace std;
class Edge {
public:
int u, v;
double percentage;
Edge() {}
Edge(int _u, int _v, double _percentage ): u(_u), v(_v), percentage(_percentage) {}
};
double min_val = -DBL_MAX;
bool BellmanFord(vector<Edge>& graph, int startVertex, int numVertex, vector<double>& percentageArr) {
// initilize
percentageArr[startVertex] = 100.0;
// relax edges repeatedly
for (int i=1; i <= numVertex -1; i++) {
for(Edge e : graph) {
if (percentageArr[e.u] != min_val) {
double newVal = percentageArr[e.u] * e.percentage / 100.0;
if (newVal> percentageArr[e.v]) {
percentageArr[e.v] = newVal;
}
}
}
}
// check for negative-weight cycles
for(Edge e : graph) {
if (percentageArr[e.u] != min_val) {
double newVal = percentageArr[e.u] * e.percentage / 100.0;
if (newVal> percentageArr[e.v]) {
return false;
}
}
}
return true;
}
int main() {
int n, m;
while (cin >> n) {
if (n == 0) {
break;
}
cin >> m;
vector<Edge> graph;
for(int i=0; i < m; i++) {
int u, v, percentage;
cin >> u >> v >> percentage;
Edge e1(u, v, percentage);
Edge e2(v, u, percentage);
graph.push_back(e1);
graph.push_back(e2);
}
vector<double> percentageArr(n+1, min_val);
BellmanFord(graph, 1, n, percentageArr);
cout << std::setprecision(6) << fixed << percentageArr[n] << " percent" << endl;
}
return 0;
}