제출 #797860

#제출 시각아이디문제언어결과실행 시간메모리
797860asdfgrace경주 (Race) (IOI11_race)C++17
100 / 100
374 ms97276 KiB
#include <bits/stdc++.h>
#include "race.h"
using namespace std;
#define DEBUG(x) //x
#define A(x) DEBUG(assert(x))
#define PRINT(x) DEBUG(cerr << x)
#define PV(x) DEBUG(cerr << #x << " = " << x << '\n')
#define PV2(x) DEBUG(cerr << #x << " = " << x.first << ',' << x.second << '\n')
#define PAR(x) DEBUG(PRINT(#x << " = { "); for (auto y : x) PRINT(y << ' '); PRINT("}\n");)
#define PAR2(x) DEBUG(PRINT(#x << " = { "); for (auto [y, z] : x) PRINT(y << ',' << z << "  "); PRINT("}\n");)
#define PAR2D(x) DEBUG(PRINT(#x << ":\n"); for (auto arr : x) {PAR(arr);} PRINT('\n'));
typedef long long i64;
const int INF = 1000000007; //998244353;

int n, k, ans;
vector<i64> pref;
vector<int> sub, dep;
vector<vector<pair<int, i64>>> edges;
vector<map<i64, int>> paths;

void dfs1(int node, int par) {
  for (auto [next, wt] : edges[node]) {
    if (next == par) continue;
    pref[next] = pref[node] + wt;
    dep[next] = dep[node] + 1;
    dfs1(next, node);
    sub[node] += sub[next];
  }
}

void dfs2(int node, int par) {
  int heavy = -1, mx = -1;
  for (auto [next, wt] : edges[node]) {
    if (next == par) continue;
    if (sub[next] > mx) {
      mx = sub[next];
      heavy = next;
    }
  }
  for (auto [next, wt] : edges[node]) {
    if (next == par || next == heavy) continue;
    dfs2(next, node);
  }
  if (heavy != -1) {
    dfs2(heavy, node);
    swap(paths[heavy], paths[node]);
  }
  if (!paths[node].count(pref[node]) || paths[node][pref[node]] > dep[node]) {
    paths[node][pref[node]] = dep[node];
  }
  for (auto [next, wt] : edges[node]) {
    if (next == par || next == heavy) continue;
    for (auto [s, d] : paths[next]) {
      if (paths[node].count(k + 2 * pref[node] - s)) {
        ans = min(ans, d + paths[node][k + 2 * pref[node] - s] - 2 * dep[node]);
      }  
    }
    for (auto [s, d] : paths[next]) {
      if (!paths[node].count(s) || paths[node][s] >= d) {
        paths[node][s] = d;
      }
    }
  }
  if (paths[node].count(k + pref[node])) {
    ans = min(ans, paths[node][k + pref[node]] - dep[node]);
  }
  PV(node); PAR2(paths[node]);
}

int best_path(int N, int K, int H[][2], int L[]) {
  n = N;
  k = K;
  edges.resize(n);
  for (int i = 0; i < n - 1; ++i) {
    edges[H[i][0]].emplace_back(H[i][1], L[i]);
    edges[H[i][1]].emplace_back(H[i][0], L[i]);
  }
  pref.resize(n, 0); sub.resize(n, 1); dep.resize(n, 0);
  dfs1(0, 0);
  paths.resize(n); ans = INF;
  dfs2(0, 0);
  return (ans == INF ? -1 : 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...