Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.18 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const long long N = 1e5 + 7, inf = 1e17;
  5.  
  6. struct e {
  7.     long long c;
  8.     int v;
  9. };
  10.  
  11. vector <e> g[N], q, Q;
  12.  
  13. int n, m, s = -1, f = -1, u[N], w, U[N];
  14.  
  15. vector <long long> d(N, inf), D(N, inf), a(N, 0);
  16.  
  17. void dfs(int v, int x) {
  18.     if (g[v].size() != 2) {
  19.         if (s == -1)
  20.             s = v;
  21.         else
  22.             if (f == -1)
  23.                 f = v;
  24.         u[v] = -1;
  25.         return;
  26.     }
  27.     u[v] = x;
  28.     for (auto i : g[v])
  29.         if (!u[i.v])
  30.             dfs(i.v, x);
  31. }
  32.  
  33. void F (int pv, int v, int e) {
  34.     U[v] = 1;
  35.     a[v] = a[pv] + e;
  36.     for (auto i : g[v])
  37.         if (!U[i.v])
  38.             F(v, i.v, i.c);
  39. }
  40.  
  41. main() {
  42.     ios_base::sync_with_stdio(0);
  43.     cin.tie(0);
  44.     freopen("input.txt", "r", stdin);
  45.  
  46.     cin >> n >> m >> w;
  47.     for (int i = 0; i < m; ++i) {
  48.         int x, y, c;
  49.         cin >> x >> y >> c;
  50.         g[--x].push_back({c, --y});
  51.         g[y].push_back({c, x});
  52.     }
  53.     for (int i = 0; i < n; ++i)
  54.         if (!u[i])
  55.             dfs(i, i + 1);
  56.     U[s] = U[f] = 1;
  57.     for (auto i : g[s])
  58.         if (!U[i.v])
  59.             F(s, i.v, i.c);
  60.     d[s] = 0;
  61.     q.push_back({0, s});
  62.     D[f] = 0;
  63.     Q.push_back({0, f});
  64.     for (int i = 0; i < q.size(); ++i) {
  65.         int u = q[i].v;
  66.         for (auto j : g[u]) {
  67.             int v = j.v;
  68.             long long c = j.c;
  69.             if (d[v] > c + d[u])
  70.                 d[v] = c + d[u],
  71.                 q.push_back({d[v], v});
  72.         }
  73.     }
  74.     for (int i = 0; i < Q.size(); ++i) {
  75.         int u = Q[i].v;
  76.         for (auto j : g[u]) {
  77.             int v = j.v;
  78.             long long c = j.c;
  79.             if (D[v] > c + D[u])
  80.                 D[v] = c + D[u],
  81.                 Q.push_back({D[v], v});
  82.         }
  83.     }
  84.     for (int i = 0; i < w; ++i) {
  85.         int x, y;
  86.         cin >> x >> y;
  87.         --x;
  88.         --y;
  89.         if (x == s && y == f || y == s && x == f) {
  90.             cout << d[f] << ' ';
  91.             continue;
  92.         }
  93.         cout << min(min({min(d[x], D[x]) + min(d[y], D[y]) + d[f], d[x] + d[y], D[x] + D[y]}), u[x] == u[y] ? abs(a[x] - a[y]) : inf) << ' ';
  94.     }
  95.  
  96.     return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement