# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
951020 | batsukh2006 | Race (IOI11_race) | C++17 | 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<race.h>
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<map>
#include<string>
#include<algorithm>
#include<vector>
#include<string.h>
#include<utility>
#include<set>
#include<cmath>
#include<queue>
#include<deque>
#include<functional>
#include<stack>
#include<limits.h>
#include<iomanip>
#include<unordered_map>
#include<numeric>
#include<tuple>
#include<bitset>
using namespace std;
#define endl '\n'
#define ff first
#define ss second
// #define int long long
#define MOD 1000000007
int n,k;
int ans=1e9;
map<int,int> mp;
const int mxN=2e5+1;
vector<bool> vis(mxN);
vector<pair<int,int> > v[mxN];
vector<int> sub(mxN),cnt(mxN);
void cal(int a, int p, int d, int w){
if(mp.count(k-w)) ans=min(ans,d+mp[k-w]);
for(auto node: v[a]){
if(node.ff!=p&&!vis[node.ff]){
cal(node.ff,a,d+1,w+node.ss);
}
}
}
void up(int a, int p, int d, int w){
if(mp.count(w)) mp[w]=min(mp[w],d);
else mp[w]=d;
for(auto node: v[a]){
if(node.ff!=p&&!vis[node.ff]){
up(node.ff,a,d+1,w+node.ss);
}
}
}
int dfs(int a, int p){
sub[a]=1;
for(auto node: v[a]){
if(node.ff!=p&&!vis[node.ff]){
sub[a]+=dfs(node.ff,a);
}
}
return sub[a];
}
int find(int a, int p, int s){
for(auto node: v[a]){
if(node.ff!=p&&!vis[node.ff]&&sub[node.ff]>s/2){
return find(node.ff,a,s);
}
}
return a;
}
void build(int a, int p){
int cd=find(a,p,dfs(a,p));
vis[cd]=1;
for(auto node: v[cd]){
if(!vis[node.ff]){
cal(node.ff,cd,1,node.ss);
up(node.ff,cd,1,node.ss);
}
}
for(auto x: mp) cnt[x.ff]=1e9;
mp.clear();
for(auto node: v[cd]){
if(!vis[node.ff]) build(node.ff,cd);
}
}
void solve(){
cin>>n>>k;
for(int i=1; i<n; i++){
int a,b,w; cin>>a>>b>>w;
v[a].push_back({b,w});
v[b].push_back({a,w});
}
mp[0]=0;
build(1,-1);
if(ans==1e9) cout<<-1;
else cout<<ans;
}
signed main(){
// freopen("file.in", "r", stdin);
// freopen("file.out", "w", stdout);
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T=1;
// cin>>T;
while(T--){
solve();
cout<<endl;
}
return 0;
}