Advertisement
Guest User

Untitled

a guest
Jun 29th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. vector<vector<int>> graph;
  8. int n, m;
  9.  
  10. void FW() {
  11.     for (int i = 0; i < n; i++) {
  12.         for (int j = 0; j < n; j++) {
  13.             for (int h = 0; h < n; h++) {
  14.                 if ((graph[j][i] != INT_MAX) && (graph[i][h] != INT_MAX)) {
  15.                     graph[j][h] = min(graph[j][h], graph[j][i] + graph[i][h]);
  16.                 }
  17.             }
  18.         }
  19.     }
  20. }
  21.  
  22. int main()
  23. {
  24.     freopen("input.txt", "r", stdin);
  25.     freopen("output.txt", "w", stdout);
  26.     cin >> n >> m;
  27.     graph.resize(n, vector<int>(n, INT_MAX));
  28.     for (int i = 0; i < n; i++) {
  29.         graph[i][i] = 0;
  30.     }
  31.     int a, b;
  32.     for (int i = 0; i < m; i++) {
  33.         cin >> a >> b;
  34.         cin >> graph[a - 1][b - 1];
  35.     }
  36.     FW();
  37.     for (int i = 0; i < n; i++) {
  38.         for (int j = 0; j < n; j++) {
  39.             if ((graph[i][j]!= INT_MAX) && (graph[j][i] != INT_MAX)) {
  40.                 graph[i][j] = 0;
  41.                 graph[j][i] = 0;
  42.             }
  43.         }
  44.     }
  45.     FW();
  46.     int k;
  47.     cin >> k;
  48.     for (int i = 0; i < k; i++) {
  49.         cin >> a >> b;
  50.         if (graph[a - 1][b - 1] != INT_MAX) {
  51.             cout << graph[a - 1][b - 1] << endl;
  52.         }
  53.         else{
  54.             cout << -1 << endl;
  55.         }
  56.     }
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement