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;
#define INIT ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define mp make_pair
#define pb push_back
#define ft first
#define sc second
#define ll long long
#define pii pair<int, int>
#define count_bits __builtin_popcount
int n, k;
vector<pii> g[200010];
bool v[200010];
int res=1e9;
int sz[200010];
void build_sz(int s){
v[s]=true;
sz[s]=1;
for(pii u:g[s]){
if(!v[u.ft]){
build_sz(u.ft);
sz[s]+=sz[u.ft];
}
}
v[s]=false;
return;
}
int find_centroid(int s, int total){
v[s]=true;
int mx=0, u=s;
for(pii node:g[s]){
if( (sz[node.ft]>mx) && (!v[node.ft]) ){
mx=sz[node.ft];
u=node.ft;
}
if( (v[node.ft]) && ((total-sz[s])>mx) ){
mx=total-sz[s]; u=node.ft;
}
}
int res;
if(v[u]){res=s;}
else{
res=find_centroid(u, total);
}
v[s]=false;
return res;
}
int k1[1000010];
void path(int s, int l, int h){
v[s]=true;
if((k1[k-l]>0) ){
res=min(res, h+k1[k-l]-1);
}
for(pii pr:g[s]){
int u=pr.ft, d=pr.sc;
if( (!v[u]) && ( (l+d)<=(k) ) ){
path(u, l+d, h+1);
}
}
if(k1[l]==0){
k1[l]=h;
}
else{
k1[l]=min(k1[l], h);
}
v[s]=false;
return ;
}
queue<int> forest;
void remove_path(int s, int l, int c){
v[s]=true;
k1[l]=0;
for(int i=g[s].size()-1; i>=0; i--){
pii pr=g[s][i];
int u=pr.ft, d=pr.sc;
if(s==c){
g[s].pop_back();
g[u].erase(find(g[u].begin(), g[u].end(), mp(s, d) ) );
forest.push(u);
}
if( (!v[u]) && ( (l+d)<=(k) ) ){
remove_path(u, l+d, c);
}
}
v[s]=false;
return ;
}
void subtask_4(){
forest.push(1);
while(!forest.empty()){
int node=forest.front(); forest.pop();
build_sz(node);
if(sz[node]==1){continue;}
int c=find_centroid(node, sz[node]);
//cout<<c<<"\n"<<flush;
k1[0]=1;
path(c, 0, 1);
remove_path(c, 0, c);
}
}
int best_path(int N, int K, int H[][2], int L[])
{
n=N; k=K;
for(int i=0; i<(n-1); i++){
int u=H[i][0]+1, v=H[i][1]+1, d=L[i];
g[u].pb({v, d}); g[v].pb({u, d});
}
subtask_4();
if(res==(1e9)){
return -1;
}
return res-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... |