# | 제출 시각 | 아이디 | 문제 | 언어 | 결과 | 실행 시간 | 메모리 |
---|---|---|---|---|---|---|---|
1244479 | bbldrizzy | 경주 (Race) (IOI11_race) | C++20 | 0 ms | 0 KiB |
#include <iostream>
#include <vector>
#include <set>
#include <bits/stdc++.h>
#define f first
#define s second
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
vector<vector<pair<int, int>>> adj;
vector<int> depth;
vector<int> dist;
vector<map<int, int>> st;
int ans = 1e9;
int n, k;
void dfs(int nd, int par) {
for (P x: adj[nd]) {
if (x.f != par) {
depth[x.f] = depth[nd]+1;
dist[x.f] = dist[nd] + x.s;
dfs(x.f, nd);
}
}
st[nd][dist[nd]] = depth[nd];
}
void dfs2(int nd, int par) {
int niga = k+2*dist[nd];
for (P x: adj[nd]) {
if (x.f != par) {
dfs2(x.f, nd);
if (st[nd].size() < st[x.f].size()) swap(st[nd], st[x.f]);
for (auto u: st[x.f]) {
if (st[nd].find(niga-u.f) != st[nd].end()) {
ans = min(ans, u.s+st[nd][niga-u.f]-2*depth[nd]);
}
}
for (auto u: st[x.f]) {
if (st[nd].find(u.f) != st[nd].end()) {
st[nd][u.f] = min(st[nd][u.f], u.s);
} else {
st[nd][u.f] = u.s;
}
}
}
}
}
int best_path(int N, int K, vector<vector<int>> H, vector<int> L) {
adj.resize(N);
depth.resize(N);
dist.resize(N);
st.resize(N);
k = K;
n = N;
for (int i = 0; i < (N-1); i++) {
int a, b, c;
a = H[i][0];
b = H[i][1];
c = L[i];
adj[a].push_back({b, c});
adj[b].push_back({a, c});
}
dfs(0, 0);
dfs2(0, 0);
return (ans==1e9 ? -1 : ans);
}