Advertisement
radmickey

Untitled

Mar 27th, 2023
656
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstdio>
  4.  
  5. #define int long long
  6. class solution {
  7. private:
  8.     std::vector<std::vector<long long>> graph;
  9.     long long n;
  10.     int m;
  11.     int k;
  12.     int q;
  13. public:
  14.  
  15.     solution() {
  16.         std::cin >> n >> m >> k;
  17.  
  18.         graph = std::vector<std::vector<long long>>(n, std::vector<long long>(n, INT64_MAX));
  19.  
  20.         for (int i = 0; i < m; i++) {
  21.             int a;
  22.             int b;
  23.             int w;
  24.  
  25.             std::cin >> a >> b >> w;
  26.             a--;
  27.             b--;
  28.             graph[a][b] = w;
  29.         }
  30.     }
  31.  
  32.     void floyd_condition() {
  33.         for (int mid = 0; mid < n; mid++) {
  34.             for (int from = 0; from < n; from++) {
  35.                 for (int to = 0; to < n; to++) {
  36.                     if (graph[from][mid] != INT64_MAX && graph[mid][to] != INT64_MAX) {
  37.                         if (std::abs(from - mid) <= k && std::abs(to - mid) <= k) {
  38.                             graph[from][to] = std::min(graph[from][to], graph[from][mid] + graph[mid][to]);
  39.                         }
  40.                     }
  41.                 }
  42.             }
  43.         }
  44.     }
  45.  
  46.     void answer() {
  47.         std::cin >> q;
  48.         while (q--) {
  49.             int a;
  50.             int b;
  51.             std::cin >> a >> b;
  52.             a--;
  53.             b--;
  54.             int ans = graph[a][b];
  55.             if (ans == INT64_MAX) {
  56.                 ans = -1;
  57.             }
  58.             std::cout << ans << '\n';
  59.         }
  60.     }
  61. };
  62.  
  63. signed main() {
  64.     solution sol;
  65.     sol.floyd_condition();
  66.     sol.answer();
  67.     return 0;
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement