Submission #1345333

#TimeUsernameProblemLanguageResultExecution timeMemory
1345333lyra_g13Roadside Advertisements (NOI17_roadsideadverts)C++20
7 / 100
39 ms18092 KiB
#include <bits/stdc++.h>
using ll = long long;
using namespace std;

// steiner tree

int main() {
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(nullptr);

  ll n;
  cin >> n;

  vector<vector<pair<ll, ll>>> adj(n + 1);
  vector<ll> depth(n + 1), weight(n + 1);

  vector<vector<ll>> bin(30, vector<ll>(n + 1));

  for (int i = 0; i < n - 1; i++) {
    ll u, v, w;
    cin >> u >> v >> w;

    adj[u].push_back({v, w});
    adj[v].push_back({u, w});
  }

  ll q;
  cin >> q;
  ll ans = 0;

  // compute
  vector<ll> vis(n + 1);

  auto dfs = [&](auto &&self, ll u) {
    if (vis[u])
      return;

    vis[u] = 1;

    for (auto [v, w] : adj[u]) {
      if (vis[v])
        continue;
      bin[0][v] = u;
      depth[v] = depth[u] + 1;
      weight[v] = weight[u] + w;
      self(self, v);
    }
  };

  dfs(dfs, 0);

  // bin lift + lca
  for (int i = 1; i < 30; i++) {
    for (int j = 1; j <= n; j++) {
      bin[i][j] = bin[i - 1][bin[i - 1][j]];
    }
  }

  auto lca = [&](ll x, ll y) {
    if (depth[x] > depth[y])
      swap(x, y);

    ll diff = depth[y] - depth[x];
    for (int i = 19; i >= 0; i--) {
      if (diff & (1 << i)) {
        y = bin[i][y];
      }
    }

    if (x == y)
      return x;

    for (int i = 19; i >= 0; i--) {
      if (bin[i][x] != bin[i][y]) {
        x = bin[i][x];
        y = bin[i][y];
      }
    }

    return bin[0][x];
  };

  auto dist = [&](ll i, ll j) -> ll {
    return weight[i] + weight[j] - 2 * weight[lca(i, j)];
  };

  // ans = cycle/2;

  while (q--) {
    vector<ll> a(5);

    for (int i = 0; i < 5; i++) {
      cin >> a[i];
    }

    ll ans = 0;
    for (int i = 0; i < 5; i++) {
      ans += dist(a[i], a[(i + 1) % 5]);
    }
    cout << ans / 2 << "\n";
  }
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...