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;
const int N = 2e5 + 1, K = 1e6 + 1;
int n, k, sz[N];
vector<pair<int, int>> g[N];
bool block[N];
void init(int u, int par) {
sz[u] = 1;
for(auto p: g[u]) if(p.first != par && !block[p.first]) {
init(p.first, u);
sz[u] += sz[p.first];
}
}
void dfs(int u, int par, int sum, int depth, map<int, int>& store) {
// cout << u << ' ' << par << endl;
for(auto p: g[u]) if(p.first != par && !block[p.first]) {
// cout << u << ' ' << p.first << ' ' << sum + p.second << ' ' << depth + 1 << endl;
if(!store.count(sum + p.second)) store[sum + p.second] = depth + 1;
else store[sum + p.second] = min(depth + 1, store[sum + p.second]);
dfs(p.first, u, sum + p.second, depth + 1, store);
}
}
int solve(int src) {
init(src, -1);
int cen = src;
while(true) {
bool found = false;
for(auto p: g[cen]) {
if(sz[p.first] < sz[cen] && sz[p.first] << 1 >= sz[src]) { // second condition guarantees no block
cen = p.first;
found = true;
break;
}
}
if(!found) break;
}
block[cen] = true;
int ans = INT_MAX;
map<int, int> f;
f[0] = 0;
for(auto p: g[cen]) if(!block[p.first]) {
map<int, int> tmp;
tmp[p.second] = 1;
dfs(p.first, -1, p.second, 1, tmp); // depth starts out at 1
for(auto mpp: tmp)
if(f.count(k - mpp.first))
ans = min(f[k - mpp.first] + mpp.second, ans);
for(auto mpp: tmp) {
if(!f.count(mpp.first)) f.insert(mpp);
else f[mpp.first] = min(mpp.second, f[mpp.first]);
}
}
// cout << cen << ":\n";
// for(auto p: f) cout << p.first << ' ' << p.second << endl;
// cout << endl;
for(auto p: g[cen]) if(!block[p.first]) ans = min(solve(p.first), ans);
return ans;
}
int best_path(int _n, int _k, int H[][2], int L[]) {
n = _n, k = _k;
for (int i = 0; i < n-1; i++) {
g[H[i][0]].emplace_back(H[i][1], L[i]);
g[H[i][1]].emplace_back(H[i][0], L[i]);
}
int res = solve(0);
return (res == INT_MAX ? -1 : res);
}
# | 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... |