forked from iamvickynguyen/Kattis-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
allpairspath.cpp
69 lines (61 loc) · 1.37 KB
/
allpairspath.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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
const ll INF = 1e18 + 10;
int main() {
ll n, m, q;
cin >> n >> m >> q;
while (!(n == 0 && m == 0 && q == 0)) {
// initialize graph
vector<vector<ll>> graph;
graph.resize(n, vector<ll>(n, INF));
for (ll i = 0; i < n; i++) {
graph[i][i] = 0; // distance to itself is 0
}
// add edges
for (ll i = 0; i < m; i++) {
ll u, v, w;
cin >> u >> v >> w;
graph[u][v] = min(graph[u][v], w);
}
// Floyd Warshall
for (ll k = 0; k < n; k++) {
for (ll i = 0; i < n; i++) {
for (ll j = 0; j < n; j++) {
if (graph[i][k] < INF && graph[k][j] < INF) {
graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j]);
}
}
}
}
// Check negative cycles
for (ll i = 0; i < n; i++) {
for (ll j = 0; j < n; j++) {
for (ll k = 0; k < n; k++) {
if (graph[k][k] < 0 && graph[i][k] != INF && graph[k][j] != INF) {
graph[i][j] = -INF;
}
}
}
}
// output
ll a, b;
for (ll i = 0; i < q; i++) {
cin >> a >> b;
if (graph[a][b] == INF) {
cout << "Impossible" << '\n';
}
else if (graph[a][b] == -INF) {
cout << "-Infinity" << '\n';
}
else {
cout << graph[a][b] << '\n';
}
}
cout << endl;
cin >> n >> m >> q;
}
return 0;
}