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 "race.h"
#define pb push_back
#define intt long long
#define mp make_pair
#define pii pair<intt,intt>
#define F first
#define S second
using namespace std;
intt n , k ;
const intt mxn = 2e5+1 ;
vector<pii> adj[mxn] ;
vector<intt> sz(mxn) , w(mxn) ,h(mxn) ;
void sub(intt a , intt p){
sz[a]=1 ;
if(p!=-1) h[a]=h[p]+1 ;
for(pii& x : adj[a]){
if(x.F==p) continue ;
w[x.F]=w[a]+x.S ;
sub(x.F,a) ;
sz[a]+=sz[x.F] ;
}
}
intt mn = 1e9 ;
vector<intt> p[mxn] ;
map<intt,multiset<intt>> cnt ;
void dfs(intt a , intt pp , intt keep){
intt bigchild = -1 , mx = -1 ;
for(pii& y : adj[a]){
intt x = y.F ;
if(x==pp) continue ;
if(sz[x]>mx){
mx=sz[x] ;
bigchild= x ;
}
}
for(pii& y : adj[a]){
intt x = y.F ;
if(x==pp||x==bigchild) continue ;
dfs(x,a,0) ;
}
if(bigchild!=-1){
dfs(bigchild,a,1) ;
swap(p[bigchild],p[a]) ;
// p[bigchild].swap(p[a]) ;
}
p[a].push_back(a) ;
intt target = k+2*w[a] ;
if(cnt.count(target-w[a])) mn = min(mn,*(cnt[target-w[a]].begin())-h[a]) ;
cnt[w[a]].insert(h[a]) ;
for(pii& y : adj[a]){
if(y.F==pp||y.F==bigchild) continue ;
for(intt& x : p[y.F]){
if(cnt.count(target-w[x])) mn = min(*(cnt[target-w[x]].begin())+h[x]-h[a]*2,mn) ;
p[a].pb(x) ;
}
for(intt& x :p[y.F]) cnt[w[a]].insert(h[x]) ;
}
if(keep==0){
for(intt& x: p[a]){
cnt[w[x]].erase(cnt[w[x]].find(h[x])) ;
if(cnt[w[x]].empty()) cnt.erase(cnt.find(w[x])) ;
}
}
}
intt solve(){
sub(1,-1) ;
dfs(1,-1,1) ;
if(mn==1e9) return -1;
return mn ;
}
int best_path(int N , int K , int H[][2] , int L[]){
n = N ;
k = K ;
/* cnt.erase(cnt.begin(),cnt.end()) ;
for(intt& x : h) x = 0 ;
for(intt& x : w) x = 0 ;
for(vector<intt>& x : p) x.erase(x.begin(),x.end()) ;
for(intt i=0;i<=n;i++) cnt[i].erase(cnt[i].begin(),cnt.end()) ;
*/if(n>100 ) return 0;
for(intt i=0;i<n;i++){
adj[H[i][0]].push_back(mp(H[i][1],L[i]));
adj[H[i][1]].push_back(mp(H[i][0],L[i])) ;
}
return solve() ;
}
# | 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... |