제출 #739615

#제출 시각아이디문제언어결과실행 시간메모리
739615Nirjhor경주 (Race) (IOI11_race)C++17
100 / 100
720 ms62572 KiB
#include "race.h"
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

using namespace std;
using namespace __gnu_pbds;

const int N = 200010;

bool bad[N];
long long weight[N];
vector <pair <int, int>> g[N];
int sub[N], ans, ptr, h[N], in[N], out[N], flat[N], target;

void trav (int u, int p = -1) {
  sub[u] = 1;
  for (auto [v, w] : g[u]) if (v != p and !bad[v]) {
    trav(v, u);
    sub[u] += sub[v];
  }
}

int centroid (int u, int bound, int p = -1) {
  for (auto [v, w] : g[u]) if (v != p and !bad[v] and sub[v] > bound) {
    return centroid(v, bound, u);
  }
  return u;
}

void go (int u, int p = -1, int depth = 0, long long sum = 0) {
  flat[++ptr] = u, in[u] = ptr;
  h[u] = depth, weight[u] = sum;

  for (auto [v, w] : g[u]) if (v != p and !bad[v]) {
    go(v, u, depth + 1, sum + w);
  }
  
  out[u] = ptr;
}

void decompose (int u = 0) {
  trav(u);
  int root = centroid(u, sub[u] / 2);
  
  ptr = 0; go(root);
  
  gp_hash_table <long long, int> smallest;
  smallest[0] = 0;

  for (auto [u, w] : g[root]) if (!bad[u]) {
    // query
    for (int i = in[u]; i <= out[u]; ++i) {
      int v = flat[i];
      long long required = target - weight[v];
      
      if (smallest.find(required) != smallest.end()) {
        ans = min(ans, h[v] + smallest[required]);
      }
    }

    // update
    for (int i = in[u]; i <= out[u]; ++i) {
      int v = flat[i];

      if (smallest.find(weight[v]) == smallest.end()) {
        smallest[weight[v]] = h[v];
      } else {
        smallest[weight[v]] = min(smallest[weight[v]], h[v]);
      }
    }
  }

  bad[root] = true;
  for (auto [v, w] : g[root]) if (!bad[v]) decompose(v);
}

int best_path (int N, int K, int H[][2], int L[]) {
  for (int i = 0; i < N - 1; ++i) {
    int u = H[i][0], v = H[i][1], w = L[i];
    g[u].emplace_back(v, w), g[v].emplace_back(u, w);
  }
  ans = INT_MAX, target = K; 
  decompose();
  if (ans == INT_MAX) ans = -1;
  return ans;
}

#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...