fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4.  
  5. int mx = 1e18;
  6. int32_t main() {
  7. ios::sync_with_stdio(false);cin.tie(nullptr);
  8. int n, m, q;
  9. cin >> n >> m >> q;
  10. // nxn matrix
  11. vector<vector<int>>matrix(n, vector<int>(n, mx));
  12. for(int i = 0; i < m; i++) {
  13. int a, b, c;
  14. cin >> a >> b >> c;
  15. a--, b--;
  16. matrix[a][b] = matrix[b][a] = min(matrix[a][b], c);
  17. }
  18. for (int i = 0; i < n; i++) {
  19. matrix[i][i] = 0;
  20. }
  21. for(int k = 0; k < n; k++) { // here k is intermediate node
  22. for(int i = 0; i < n; i++) {
  23. for(int j = 0; j < n; j++) {
  24. matrix[i][j] = min(matrix[i][j], matrix[i][k]+matrix[k][j]);
  25. }
  26. }
  27. }
  28. // query
  29. while(q--) {
  30. int a, b;
  31. cin >> a >> b;
  32. a--, b--;
  33. if(matrix[a][b] == mx) cout << "-1\n";
  34. else cout << matrix[a][b] << "\n";
  35. }
  36. return 0;
  37. }
Success #stdin #stdout 0s 5264KB
stdin
4 3 5
1 2 5
1 3 9
2 3 3
1 2
2 1
1 3
1 4
3 2
stdout
5
5
8
-1
3