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>
using namespace std ;
const int mx = 2e5 + 5 , ww = 1e7 + 6 ;
vector<pair<int,int> > adj[mx] ;
int subtree[mx] , vis[mx] , dist[ww] , n , ans = mx , k ;
void dfs(int s , int par)
{
int siz = adj[s].size() ;
subtree[s] = 1 ;
for(int i = 0 ; i < siz ; ++i)
{
if(adj[s][i].first!=par && vis[adj[s][i].first]==0)
{
dfs(adj[s][i].first,s) ;
subtree[s] += subtree[adj[s][i].first] ;
}
}
}
int centroid(int s , int par , int n)
{
int siz = adj[s].size() ;
for(int i = 0 ; i < siz ; ++i)
{
if(adj[s][i].first!=par && vis[adj[s][i].first]==0)
{
if((subtree[adj[s][i].first])>n) return centroid(adj[s][i].first,s,n) ;
}
}
return s ;
}
void findans(int s , int p , int num , int sum)
{
if(sum<=k) ans = min(ans,num + dist[k-sum]) ;
int siz = adj[s].size() ;
for(int i = 0 ; i < siz ; ++i)
{
if(vis[adj[s][i].first]==0 && adj[s][i].first!=p)
{
findans(adj[s][i].first,s,num+1,sum+adj[s][i].second) ;
}
}
}
void addcnt(int s , int p , int num , int sum)
{
if(sum<=k) dist[sum] = min(dist[sum],num) ;
int siz = adj[s].size() ;
for(int i = 0 ; i < siz ; ++i)
{
if(vis[adj[s][i].first]==0 && adj[s][i].first!=p) addcnt(adj[s][i].first,s,num+1,sum+adj[s][i].second) ;
}
}
void eras(int s , int p , int sum)
{
if(sum<=k) dist[sum] = mx ;
int siz = adj[s].size() ;
for(int i = 0 ; i < siz ; ++i)
{
if(adj[s][i].first != p && vis[adj[s][i].first]==0)
{
eras(adj[s][i].first,s,sum+adj[s][i].second) ;
}
}
}
void decomp(int s , int par)
{
dfs(s,par) ;
int c = centroid(s,par,subtree[s]/2) ;
vis[c] = 1 ;
int siz = adj[c].size() ;
dist[0] = 0 ;
for(int i = 0 ; i < siz ; ++i)
{
int v = adj[c][i].first ;
if(!vis[v])
{
findans(v,c,1,adj[c][i].second) ;
addcnt(v,c,1,adj[c][i].second) ;
}
}
for(int i = 0 ; i < siz ; ++i)
{
int v = adj[c][i].first ;
if(!vis[v])
{
eras(v,c,adj[c][i].second) ;
}
}
for(int i = 0 ; i < siz ; ++i)
{
if(!vis[adj[c][i].first]) decomp(adj[c][i].first,c) ;
}
}
int best_path(int a , int b , int H[][2] , int L[])
{
n = a , k = b ;
for(int i = 0 ; i < n - 1 ; ++i)
{
int ww = H[i][0] , vv = H[i][1] ;
adj[ww].push_back({vv,L[i]}) ;
adj[vv].push_back({ww,L[i]}) ;
}
for(int i = 0 ; i <= k ; ++i) dist[i] = mx ;
decomp(0,-1) ;
if(ans==mx) return -1 ;
else 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... |