#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 <pii> g[N1];
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 ii : g[v] )
{
int to = ii.F;
if( to == p || was_centroid[to] ) continue;
dfs( to, v ), sz[v] += sz[to];
}
}
int find_centroid( int v, int p )
{
for( auto ii : g[v] )
{
int to = ii.F;
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 )
{
if( d <= k && cnt[d] != -1 ) ans = min( ans, op + cnt[d] );
for( auto ii : g[v] )
{
int to = ii.F;
if( to == p || was_centroid[to] ) continue;
add( to, v, d + ii.S, op + 1 );
}
}
void upd( int v, int p, int d, int tp, int op )
{
if( d <= k )
{
if( tp == -1 ) cnt[d] = -1;
else cnt[d] = ( cnt[d] == -1 ? op : min( cnt[d], op ));
}
for( auto ii : g[v] )
{
int to = ii.F;
if( to == p || was_centroid[to] ) continue;
upd( to, v, d + ii.S, 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 ii : g[v] )
{
int to = ii.F;
if( !was_centroid[to] )
{
add( to, v, ii.S, 1 );
upd( to, v, ii.S, 1, 1 );
}
}
for( auto to : g[v] ) if( !was_centroid[to.F] ) upd( to.F, v, to.S, -1, 1 );
for( auto to : g[v] ) if( !was_centroid[to.F] ) centroid_decomposition(to.S);
}
int best_path( int N, int K, int H[][2], int L[] )
{
n = N, k = K;
FOR( i, 0, K, 1 ) cnt[i] = -1;
FOR( i, 1, n - 1, 1 )
{
z = L[i - 1]; x = H[i - 1][0] + 1, y = H[i - 1][1] + 1;
g[x].pb({ y, z }), g[y].pb({ x, z });
}
ans = inf;
centroid_decomposition(1);
if( ans == inf ) ans = -1;
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... |