This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define S second
#define F first
#define pii pair<ll,ll>
#define vi vector <ll>
#define vvi vector <vi>
#define vvvi vector <vvi>
#define vp vector <pii>
#define vvp vector <vp>
#define vb vector <bool>
#define vvb vector <vb>;
#define INF INT_MAX
#define MOD 998244353
#define MAXN 200000
#pragma GCC optimize("O3,unroll-loops")
using namespace std;
vvp adj(MAXN);
vb deleted(MAXN);
vi s(MAXN);
ll k;
void up(ll v,ll p){
if (deleted[v])s[v]=0;else{
s[v]=1;
for (auto& [to,w]:adj[v]){
if (to==p)continue;
up(to,v);
s[v]+=s[to];
}
}
}
ll find(ll v,ll p,ll n){
for (auto& [to,w]:adj[v])
if (to!=p && !deleted[to] && s[to]>n/2)
return find(to,v,n);
return v;
}
vi cnt(1000001,INF);
ll ans=INF;
void add(ll v,ll p,ll dist,ll depth){
if (dist>k)return;
cnt[dist]=min(cnt[dist],depth);
for (auto& [to,w]:adj[v])
if (to!=p && !deleted[to])
add(to,v,dist+w,depth+1);
}
void calc(ll v,ll p,ll dist,ll depth){
if (dist>k)return;
ans=min(ans,depth+cnt[k-dist]);
// cout<<v<<" "<<p<<" "<<dist<<" "<<depth<<" "<<cnt[k-dist]<<"\n";
for (auto& [to,w]:adj[v])
if (to!=p && !deleted[to])
calc(to,v,dist+w,depth+1);
}
void remove(ll v,ll p,ll dist){
if (dist>k)return;
cnt[dist]=INF;
for (auto& [to,w]:adj[v])
if (to!=p && !deleted[to])
remove(to,v,dist+w);
}
void build(ll v){
up(v,-1);
ll c=find(v,-1,s[v]);
cnt[0]=0;
for (auto& [to,w]:adj[c]){
if (!deleted[to]){
add(to,c,w,1);
}
}
for (auto& [to,w]:adj[c]){
if (!deleted[to]){
calc(to,c,w,1);
}
}
for (auto& [to,w]:adj[c]){
if (!deleted[to]){
remove(to,c,w);
}
}
deleted[c]=true;
for (auto &[to,w]:adj[c])if (!deleted[to])build(to);
}
int best_path(int N, int K, int H[][2], int L[]){
k=K;
for (ll i=0;i<N-1;i++){
adj[H[i][0]].pb({H[i][1],L[i]});
adj[H[i][1]].pb({H[i][0],L[i]});
}
build(0);
if (ans==INF)return -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... |