#include "race.h"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define pii pair<int,int>
#define fir first
#define sec second
#define sz(x) ll(x.size())
// #define int long long
const int maxn = 2e5 + 5;
map<int, int> mp[maxn]; // mp[u][x] is length of minimum path with u as root and sum = x. (sum, min edges)
vector<pii> adj[maxn], off(maxn);
int n, k, ans = maxn;
void dfs(int u, int p) {
mp[u][0] = 0;
for(auto &i : adj[u]) {
int w = i.sec, v = i.fir;
if(v == p) continue;
dfs(v, u);
off[v].fir += w;
off[v].sec++;
// mp[u][w] = 1;
if(sz(mp[u]) < sz(mp[v])) {
swap(mp[u], mp[v]);
swap(off[u], off[v]);
}
for(auto &x : mp[v]) {
int z = k-x.fir-off[v].fir-off[u].fir;
if(mp[u].count(z)) {
ans = min(ans, mp[u][z] + x.sec + off[u].sec + off[v].sec);
}
}
for(auto &x : mp[v]) {
int z = x.fir + off[v].fir - off[u].fir;
if(mp[u].count(z))
mp[u][z] = min(mp[u][z], x.sec + off[v].sec - off[u].sec);
else
mp[u][z] = x.sec + off[v].sec - off[u].sec;
}
}
}
int best_path(int N, int K, int H[][2], int L[])
{
n = N, k = K;
for(int i=0; i<n-1; ++i) {
adj[H[i][0]].push_back({H[i][1], L[i]});
adj[H[i][1]].push_back({H[i][0], L[i]});
}
dfs(0, -1);
return (ans == maxn ? -1 : ans);
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |