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;
typedef long long ll;
#define debug(x) cout<<#x<<" = "<<x<<endl
struct edge
{
int to;
int w;
};
int blocked[200005];
vector<edge> adjList[200005];
int subtree_size[200005];
void computeSize(int u,int p)
{
subtree_size[u]=1;
for(edge e: adjList[u]){
int v=e.to;
if(blocked[v] || v==p) continue;
computeSize(v,u);
subtree_size[u]+=subtree_size[v];
}
}
int findCentroid(int root)
{
computeSize(root,-1);
int n=subtree_size[root];
int u=root;
bool found=false;
do{
found=true;
for(edge e: adjList[u]){
int v=e.to;
if(blocked[v]) continue;
if(subtree_size[v]>n/2){
found=false;
subtree_size[u]-=subtree_size[v];
subtree_size[v]+=subtree_size[u];
u=v;
break;
}
}
}while(!found);
return u;
}
int k;
int minimum=INT_MAX;
void dfs(int u,int p,int distRoot,int depth,map<int, multiset<int> >& dist)
{
if(distRoot>k)
return;
dist[distRoot].insert(depth);
for(edge e: adjList[u]){
int v=e.to;
if(blocked[v] || v==p) continue;
dfs(v,u,distRoot+e.w,depth+1,dist);
}
}
typedef pair<int, multiset<int> > pii;
void decompose(int root)
{
int centroid=findCentroid(root);
map<int, multiset<int> > dist;
dfs(centroid,-1,0,0,dist);
if(dist[k].size()>0 && *(dist[k].begin())>0)
minimum=min(minimum,*(dist[k].begin()));
for(pii x: dist){
if(k%2==0 && x.first==k/2){ //Special case
int i=0;
int value=0;
for(int edges: x.second){
if(i==2) break;
value+=edges;
i++;
}
if(i==2) minimum=min(minimum,value);
continue;
}
if(x.second.size()==0 || dist[abs(k-x.first)].size()==0) continue;
int value_1=*(x.second.begin());
int value_2=*(dist[abs(k-x.first)].begin());
if(value_1!=0 && value_2!=0)
minimum=min(minimum,value_1+value_2);
}
dist.clear();
blocked[centroid]=1;
for(edge e: adjList[centroid]){
int v=e.to;
if(blocked[v]) continue;
decompose(v);
}
}
int best_path(int n, int K, int H[][2], int L[])
{
k=K;
for(int i=0;i<n-1;i++){
int a=H[i][0];
int b=H[i][1];
int w=L[i];
adjList[a].push_back({b,w});
adjList[b].push_back({a,w});
}
decompose(0);
return (minimum!=INT_MAX)? minimum : -1;
}
# | 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... |