This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//!yrt tsuj uoy srettam gnihton no emoc
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
#define pb push_back
#define mp make_pair
#define pii pair <int, int>
#define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define F first
#define S second
const int maxn = 1e5 + 5, maxk = 1e6 + 5;
vector <pii> adj[maxn];
int w[maxn], sz[maxn];
int h[maxn], d[maxn], mn[maxk];
int n, k;
int inf = 1e9 + 7, ans = 1e9 + 7;
bool dead[maxn];
vector <int> vec;
void DFS(int v, int p = -1){
for(auto u : adj[v]){
if(u.F != p){
h[u.F] = h[v] + 1;
d[u.F] = d[v] + w[u.S];
DFS(u.F, v);
}
}
}
void dfs(int v, int p = -1){
sz[v] = 1;
vec.pb(v);
for(auto u : adj[v]){
if(u.F != p && !dead[u.F]){
dfs(u.F, v);
sz[v] += sz[u.F];
}
}
}
int find_centroid(int v, int p, int z){
for(auto u : adj[v]){
if(u.F != p && !dead[u.F] && sz[u.F] > z / 2){
return find_centroid(u.F, v, z);
}
}
return v;
}
void get(int v, int p, int he, int di){
if(k - d[v] + di >= 0 && k - d[v] + di < maxk){
ans = min(mn[k - d[v] + di] + h[v] - he, ans);
}
for(auto u : adj[v]){
if(u.F != p && !dead[u.F]){
get(u.F, v, he, di);
}
}
}
void upd(int v, int p, int he, int di){
if(d[v] - di >= 0 && d[v] - di < maxk){
mn[d[v] - di] = min(h[v] - he, mn[d[v] - di]);
}
for(auto u : adj[v]){
if(u.F != p && !dead[u.F]){
upd(u.F, v, he, di);
}
}
}
void solve(int v){
dfs(0);
int c = find_centroid(v, -1, sz[v]);
dead[c] = true;
vec.clear();
for(auto x : adj[c]){
int u = x.F;
if(!dead[u]){
get(u, c, h[c], d[c]);
upd(u, c, h[c], d[c]);
}
}
ans = min(ans, mn[k]);
for(int u : vec){
if(d[u] >= 0 && d[u] < maxk - 2){
mn[d[u]] = inf;
}
}
for(auto x : adj[c]){
if(!dead[x.F]){
solve(x.F);
}
}
}
///*
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 x = H[i][0], y = H[i][1];
adj[x].push_back({y, i});
adj[y].push_back({x, i});
}
for(int i = 0; i < n - 1; i ++)
w[i] = L[i];
for(int i = 0; i < maxk - 2; i ++){
mn[i] = inf;
}
DFS(0);
solve(0);
if(ans >= inf){
ans = -1;
}
return ans;
}
//*/
/*
int main(){
fast_io;
cin >> n >> k;
for(int i = 0; i < n - 1; i ++){
int x, y;
cin >> x >> y;
adj[x].pb({y, i});
adj[y].pb({x, i});
}
for(int i = 0; i < n - 1; i ++){
cin >> w[i];
}
for(int i = 0; i < maxk - 2; i ++){
mn[i] = inf;
}
DFS(0);
solve(0);
if(ans >= inf){
cout << -1;
}
else{
cout << ans;
}
return 0;
}
*/
# | 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... |