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<bits/stdc++.h>
using namespace std;
vector<set<pair<int,int>>>adj(1e5);
int k=0;
vector<int>parent(1e5,-1);
vector<int>sub(1e5,0);
vector<vector<int>>sparce(1e5,vector<int>(20,-1));
vector<int>depth(1e5,0);
vector<int>ans(1e5,0);
vector<int>aux(1e5,0);
int answer = INT_MAX;
int kk = -1;
int bookmark = 0;
void dfs (int cur,int par,int cost,int len,int fill){
if (fill){
if (aux[cost]<bookmark){
aux[cost] = bookmark;
ans[cost] = len;
}
else if (len<ans[cost]){
ans[cost] = len;
aux[cost] = bookmark;
}
}
else{
if (aux[kk - cost]==bookmark){
if (len + ans[kk - cost]<answer){
answer = min(answer,len + ans[kk-cost]);
}
if (cost ==kk){
answer = min(answer,len);
}
}
}
for (auto x:adj[cur]){
if (x.first!=par){
dfs(x.first,cur,cost + x.second,len + 1,fill);
}
}
}
void getsub(int u,int par){
sub[u]=1;
k++;
for (auto x:adj[u]){
if (x.first!=par){
getsub(x.first,u);
sub[u]+=sub[x.first];
}
}
}
int getcentroid(int u,int par){
for (auto x:adj[u]){
if (x.first!=par){
if (sub[x.first]>k/2){
return getcentroid(x.first,u);
}
}
}
return u;
}
void decomposition(int u,int par){
k = 0;
getsub(u,u);
int c = getcentroid(u,u);
if (par==-1){
par=c;
}
parent[c]=par;
bookmark++;
for (auto x:adj[c]){
dfs(x.first,c,x.second,1,0);
dfs(x.first,c,x.second,1,1);
}
for (auto x:adj[c]){
adj[x.first].erase({c,x.second});
//adj[c].erase(x);
decomposition(x.first,c);
}
}
void build(){
ans[0] = 0;
decomposition(0,-1);
}
void getsparce(int u,int par){
for (auto x:adj[u]){
if (x.first!=par){
sparce[x.first][0] = u;
depth[x.first]=depth[u]+1;
getsparce(x.first,u);
}
}
}
int lca(int u,int v){
if (depth[u]<depth[v]){
swap(u,v);
}
for (int i = 19;i>=0;--i){
if (sparce[u][i]!=-1)
if (depth[sparce[u][i]]>=depth[v]){
u=sparce[u][i];
}
}
if (u==v)return u;
for (int i = 19;i>=0;--i){
if (sparce[u][i]!=sparce[v][i]){
u=sparce[u][i];
v=sparce[v][i];
}
}
return sparce[u][0];
}
int dist(int u,int v){
int l = lca(u,v);
return depth[u] + depth[v] - 2*depth[l];
}
void preprocess(int n){
getsparce(0,-1);
for (int i = 1;i<20;++i){
for (int j = 0;j<n;++j){
if (sparce[j][i-1]!=-1){
sparce[j][i] = sparce[sparce[j][i-1]][i-1];
}
}
}
}
int best_path(int N, int K, int H[][2], int L[])
{
kk = K;
for (int i = 0;i<N-1;++i){
adj[H[i][0]].insert({H[i][1],L[i]});
adj[H[i][1]].insert({H[i][0],L[i]});
}
build();
if (answer==INT_MAX){
return -1;
}
return answer;
}
| # | 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... |