# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1272141 | efeg | Race (IOI11_race) | C++20 | 0 ms | 0 KiB |
#include <bits/stdc++.h>
using namespace std;
#include "race.h"
#define int long long
#define pb push_back
#define F first
#define S second
const int maxN = 2e5 + 100;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector<ii> vii;
vector<vii> adj;
vi dist,depth;
set<ii> st[maxN];
int n,k,ans = maxN;
void calDist(int node,int p){
for (auto tp : adj[node]){
int to,w; tie(to,w) = tp;
if (to == p) continue;
dist[to] = dist[node] + w;
depth[to] = depth[node] + 1;
calDist(to,node);
}
}
void dfs(int node,int p){
st[node].insert({dist[node],depth[node]});
for (auto tp : adj[node]){
int to,w; tie(to,w) = tp;
if (to == p) continue;
dfs(to,node);
if (st[node].size() < st[to].size()) swap(st[node],st[to]);
for (auto x : st[to]){
int tmp = k + 2 * dist[node] - x.F;
auto itr = st[node].lower_bound({tmp,-maxN});
if (itr == st[node].end() || itr->F != tmp) continue;
else {
ans = min(ans,x.S + itr->S - 2 * depth[node]);
}
}
for (auto x : st[to]){
st[node].insert(x);
}
}
}
int best_path(int N, int K, int h[][2], int l[])
{
n = N; k = K;
adj.assign(n+10,vii());
dist.assign(n+10,0);
depth.assign(n+10,0);
for (int i = 0; i < n-1; i++){
int u = h[i][0], v = h[i][1], w = l[i];
adj[u].emplace_back(v,w);
adj[v].emplace_back(u,w);
}
depth[0] = 0;
dist[0] = 0;
calDist(0,-1);
dfs(0,-1);
return (ans == maxN ? -1 : ans);
}