# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
41018 | Hassoony | 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>
#include<unordered_map>
using namespace std;
typedef double D;
typedef long long ll;
const ll mod=1e9+7;
const ll inf=(1ll<<62);
const int SQ=400;
const int MX=2e5+9;
int n,a,b,subtree[MX],blocked[MX],par[MX],depth[MX],k,dis[MX];
vector<pair<int,int> >v[MX];
vector<int>f;
ll ans=0;
unordered_map<int,int>cnt;
void dfs_size(int x,int p){
subtree[x]=1;par[x]=p;
for(auto pp:v[x]){
if(pp.first==p||blocked[pp.first])continue;
dfs_size(pp.first,x);
subtree[x]+=subtree[pp.first];
}
}
vector<int>nodes;
void DFS(int x,int p,int sum){
if(sum>k)return;
f.push_back(x);
nodes.push_back(x);
dis[x]=sum;
for(auto pp:v[x]){
if(pp.first==p||blocked[pp.first])continue;
depth[pp.first]=depth[x]+1;
DFS(pp.first,x,sum+pp.second);
}
}
void create(int x){
dfs_size(x,-1);
int S=subtree[x],idx;
queue<int>q;
q.push(x);
while(!q.empty()){
int nxt=q.front();q.pop();
int s=subtree[x]-subtree[nxt];
for(auto pp:v[nxt]){
if(pp.first==par[nxt]||blocked[pp.first])continue;
s=max(s,subtree[pp.first]);
q.push(pp.first);
}
if(S>s){
S=s;
idx=nxt;
}
}
for(auto pp:f){
cnt[dis[pp]]=0;
dis[pp]=depth[pp]=0;
}
f.clear();
blocked[idx]=1;
cnt[0]=0;
dis[idx]=depth[idx]=0;
for(auto pp:v[idx]){
if(blocked[pp.first])continue;
depth[pp.first]=1;
DFS(pp.first,idx,pp.second);
for(auto nxt:nodes){
if(k-dis[nxt]<0)continue;
if(dis[nxt]==k)ans=min(ans,(ll)depth[nxt]);
if(cnt[k-dis[nxt]]==0)continue;
ans=min(ans,(ll)depth[nxt]+cnt[k-dis[nxt]]);
}
for(auto i:nodes){
if(cnt[dis[i]]==0){cnt[dis[i]]=depth[i];}
else cnt[dis[i]]=min(cnt[dis[i]],depth[i]);
}
nodes.clear();
}
// cout<<"answer: "<<ans<<endl;
for(auto pp:v[idx]){
if(blocked[pp.first])continue;
create(pp.first);
}
}
int c;
int main(){
scanf("%d%d",&n,&k);
for(int i=0;i<n-1;i++){
scanf("%d%d%d",&a,&b,&c);
v[a].push_back({b,c});
v[b].push_back({a,c});
}
ans=inf;
create(1);
if(ans==inf)puts("-1");
else cout<<ans<<endl;
}