| 130 | } |
| 131 | |
| 132 | int johnson(int t_no, int n, int m) { |
| 133 | |
| 134 | // step 1: create a new vertex (0) and add edge from it to all other vertices |
| 135 | for (int i = 1; i <= n; i ++) { |
| 136 | edges.push_back({0, {i, 0}}); |
| 137 | } |
| 138 | |
| 139 | // step 2: run bellman ford with (0) as the source |
| 140 | vector <int> h(n + 1, INT_MAX); |
| 141 | h[0] = 0; |
| 142 | bool negative_cycle = bellman_ford(0, n + 1, m + n, h); |
| 143 | if (negative_cycle) { |
| 144 | return 0; |
| 145 | } |
| 146 | else { |
| 147 | cout << "graph " << t_no + 1 << " "; |
| 148 | cout << "yes" << endl << endl; |
| 149 | |
| 150 | // print the h_vector |
| 151 | for (int i = 1; i <= n; i ++) { |
| 152 | cout << h[i] << " "; |
| 153 | } |
| 154 | cout << "0"; // h(n + 1), i.e. new vertex |
| 155 | cout << endl << endl; |
| 156 | } |
| 157 | |
| 158 | // step 3: reweight all the edges of the original graph |
| 159 | // wt'(u, v) = wt(u, v) + h[u] - h[v] |
| 160 | |
| 161 | for (int i = 0; i < m; i ++) { |
| 162 | pair <int, pair <int, int> > edge; |
| 163 | edge = edges[i]; |
| 164 | int first_node = edge.first; |
| 165 | int second_node = edge.second.first; |
| 166 | int weight = edge.second.second; |
| 167 | weight += h[first_node] - h[second_node]; |
| 168 | adj_new[first_node].push_back({second_node, weight}); |
| 169 | } |
| 170 | |
| 171 | // step 4: run dijkstra's algo for all the vertices 1 to n |
| 172 | // in the graph formed by adj_new |
| 173 | |
| 174 | vector <vector <int> > all_pair_dist; |
| 175 | vector <int> cur_dist; |
| 176 | for (int i = 1; i <= n; i ++) { |
| 177 | cur_dist.assign(n + 1, INT_MAX); |
| 178 | dijkstra(i, n, m, cur_dist, h); |
| 179 | all_pair_dist.push_back(cur_dist); |
| 180 | } |
| 181 | |
| 182 | // print the all-pair shortest paths |
| 183 | for (int i = 0; i < n; i ++) { |
| 184 | for (int j = 1; j <= n; j ++) { |
| 185 | if (all_pair_dist[i][j] != INT_MAX) { |
| 186 | cout << all_pair_dist[i][j] << " "; |
| 187 | } |
| 188 | else { |
| 189 | cout << "# "; |
no test coverage detected