# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
853638 | Dzadzo | Race (IOI11_race) | C++14 | 0 ms | 0 KiB |
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 int ll
#define pb push_back
#define S second
#define F first
#define pii pair<int,int>
#define vi vector <int>
#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);
int k;
void up(int v,int 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];
}
}
}
int find(int v,int p,int 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);
int ans=INF;
void add(int v,int p,int dist,int 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(int v,int p,int dist,int 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(int v,int p,int 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(int v){
up(v,-1);
int 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);
}
int32_t best_path(int N, int K, int H[][2], int L[]){
k=K;
for (int 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;
}