#include <bits/stdc++.h>
 
#define respagold ios_base::sync_with_stdio(0), cin.tie(0);
#define ll long long
//#define int long long
#define int2 __int128_t
#define FOR( i, x, n, d ) for( int i = x; i <= n; i += d )
#define FORR( i, x, n, d ) for( int i = x; i >= n; i -= d )
#define F first
#define S second
#define all(x) x.begin(), x.end()
//#define sz(x) (int)(x.size())
#define pb push_back
#define ins insert
#define lb lower_bound
#define ub upper_bound
#define pii pair <int, int>
#define mkp make_pair
 
using namespace std;
 
const int N1 = 3e5 + 123;
const int inf = 1e9;
const int MOD1 = 1e9 + 7;
const int MOD = 998244353;
const int P = 6547;
 
int a[N1], b[N1], n, m, k, x, y, z, w, siz, was_centroid[N1], sz[N1], pa[N1], ans;
vector <int> g[N1];
map <pii, int> mp;
int cnt[1000005];
 
mt19937 rng( chrono::steady_clock::now().time_since_epoch().count());
 
int rand( int l, int r )
{
    uniform_int_distribution <int> uid( l, r );
    return uid( rng );
}
void dfs( int v, int p )
{
	sz[v] = 1;
	
	for( auto to : g[v] ) 
	{
		if( to == p || was_centroid[to] ) continue;
		dfs( to, v ), sz[v] += sz[to];
	}
}
int find_centroid( int v, int p )
{
	for( auto to : g[v] )
	{
		if( to == p || was_centroid[to] ) continue;
		if( sz[to] * 2 > siz ) return find_centroid( to, v );
	}
	return v;
}
void add( int v, int p, int d, int op )
{
	d += mp[{v, p}];
	if( d <= k && cnt[d] != -1 ) ans = min( ans, op + cnt[d] );
	
	for( auto to : g[v] ) 
	{
		if( to == p || was_centroid[to] ) continue;
		add( to, v, d, op + 1 );
	}
}
void upd( int v, int p, int d, int tp, int op )
{
	d += mp[{v, p}];
	
	if( d <= k ) 
	{
		if( tp == -1 ) cnt[d] = -1;
		else cnt[d] = ( cnt[d] == -1 ? op : min( cnt[d], op ));
	}
	for( auto to : g[v] ) 
	{
		if( to == p || was_centroid[to] ) continue;
		upd( to, v, d, tp, op + 1 );
	}
}
void centroid_decomposition( int v )
{
	dfs(v, 0); siz = sz[v];
	v = find_centroid(v, 0);
	was_centroid[v] = 1; cnt[0] = 0;
	
	for( auto to : g[v] )
	{
		if( !was_centroid[to] )
		{
			add( to, v, 0, 1 );
			upd( to, v, 0, 1, 1 );
		}
	}
	for( auto to : g[v] ) if( !was_centroid[to] ) upd( to, v, 0, -1, 1 );
	for( auto to : g[v] ) if( !was_centroid[to] ) centroid_decomposition(to);
}
int best_path( int N, int K, int H[][2], int L[] )
{
	n = N, k = K;
	
	FOR( i, 1, n - 1, 1 ) tie( a[i], b[i] ) = make_pair( H[i - 1][0], H[i - 1][1] );
	memset( cnt, -1, sizeof cnt );
	
	FOR( i, 1, n - 1, 1 )
	{
		z = L[i - 1]; x = a[i] + 1, y = b[i] + 1;
		g[x].pb(y), g[y].pb(x);
		mp[{x, y}] = mp[{y, x}] = z;
	}
	ans = inf;
	centroid_decomposition(1);
	return (ans == inf ? -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... |