이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include "race.h"
#include<iostream>
#include<utility>
#include<vector>
#include<map>
using namespace std;
const int N = 2e5+5;
int sz[N];
int st[N];
int ft[N];
int ver[N];
int orig_len[N];
int orig_sum[N];
map<int,int> mem;
vector<pair<int,int>> g[N];
int t;
int ans = 1e9;
void preprocess(int u,int len=0,int sum=0,int p = -1){
++t;
st[u] = t;
ver[t] = u;
orig_sum[u] = sum;
orig_len[u] = len;
sz[u] = 1;
for(auto &x:g[u]){
if(x.first!=p){
preprocess(x.first,len+1,sum+x.second,u);
sz[u]+=sz[x.first];
}
}
ft[u] = t;
}
void solve(int u,int target,int p = -1,bool keep = false){
int mx = -1,big_child = -1,del_sum = orig_sum[u],del_len = orig_len[u];
for(auto &x:g[u]) if(x.first!=p&&sz[x.first]>mx) mx = sz[x.first],big_child = x.first;
for(auto &x:g[u]){
if(x.first!=p&&x.first!=big_child){
solve(x.first,target,u,false);
}
}
if(big_child!=-1){
solve(big_child,target,u,true);
}
int need = target-orig_sum[u]+2*del_sum;
if(need>=0&&need<=1000000&&mem[need]) ans = min(ans,mem[need]+orig_len[u]-2*del_len);
if(!mem[orig_sum[u]]) mem[orig_sum[u]] = orig_len[u];
mem[orig_sum[u]] = min(mem[orig_sum[u]],orig_len[u]);
for(auto &x:g[u]){
if(x.first!=p&&x.first!=big_child){
for(int i=st[x.first];i<=ft[x.first];i++){
int v = ver[i];
need = target-orig_sum[v]+2*del_sum;
if(need>=0&&need<=1000000&&mem[need]) ans = min(ans,mem[need]+orig_len[v]-2*del_len);
if(!mem[orig_sum[v]]) mem[orig_sum[v]] = orig_len[v];
mem[orig_sum[v]] = min(mem[orig_sum[v]],orig_len[v]);
}
}
}
if(!keep){
for(int i=st[u];i<=ft[u];i++){
mem.erase(orig_sum[ver[i]]);
}
}
}
int best_path(int N, int K, int H[][2], int L[])
{
for(int i=0;i<N;i++) g[H[i][0]].push_back({H[i][1],L[i]}),g[H[i][1]].push_back({H[i][0],L[i]});
preprocess(0);
solve(0,K);
if(ans>=N) return -1;
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... |