#pragma GCC optimize("-O3")
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#define ll long long
#define ld long double
#define vl vector<ll>
#define vi vector<int>
#define pii pair<int, int>
#define pll pair<ll, ll>
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
#define pb push_back
#define p_b pop_back
#define f first
#define s second
using namespace std;
using namespace __gnu_pbds;
typedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
const int sz = 2e5+5;
vector<pii>g[sz];
set<int>st[sz];
map<int, int>mp[sz];
int vis[sz], val[sz], lev[sz], n, k, ans = INT_MAX;
void dfs(int node)
{
vis[node] = 1;
for(auto [u, w] : g[node])
{
if(vis[u])
continue;
lev[u] = lev[node] + 1;
val[u] = val[node] + w;
dfs(u);
}
}
void dfs2(int node)
{
vis[node] = 1;
st[node].insert(val[node]);
mp[node][val[node]] = lev[node];
for(auto [u, w] : g[node])
{
if(vis[u])
continue;
dfs2(u);
if(st[node].size() < st[u].size())
{
swap(st[node], st[u]);
swap(mp[node], mp[u]);
}
for(auto h : st[u]){
if(mp[node][k+2*val[node]-h] != 0)
ans = min(ans, mp[node][k+2*val[node]-h] + mp[u][h] - 2 * lev[node]);
}
for(auto h : st[u])
{
st[node].insert(h);
if(mp[node][h] == 0)
mp[node][h] = mp[u][h];
else
mp[node][h] = min(mp[node][h], mp[u][h]);
}
}
if(mp[node][val[node]+k] != 0)
ans = min(ans, mp[node][val[node]+k] - lev[node]);
}
int best_path(int N, int K, int H[][2], int L[])
{
n = N, k = K;
for(int i = 0; i < N - 1; i++)
{
g[H[i][0]].pb({H[i][1], L[i]});
g[H[i][1]].pb({H[i][0], L[i]});
}
dfs(0);
for(int i = 0; i < N; i++)
vis[i] = 0;
dfs2(0);
if(ans == INT_MAX)
return -1;
else
return 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... |