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 <bits/stdc++.h>
using namespace std;
#define nmax 200020
#define ii pair<int, int>
#define ll long long
int n, k, ans, cnt[1000100], sz[nmax], r[nmax];
vector<ii> adj[nmax];
inline void minimize(int &a, int b)
{
if(a == -1 || a > b)
a = b;
}
int dfs(int u, int p = -1)
{
sz[u] = 1;
for(auto [C, v]: adj[u]) {
if(v != p && !r[v]) sz[u] += dfs(v, u);
}
return sz[u];
}
int get_centroid(int m, int u, int p = -1)
{
for(auto [C, v]: adj[u]) {
if(v != p && !r[v] && 2 * sz[v] > m) return get_centroid(m, v, u);
}
return u;
}
void get_cnt(int sum, bool filling, int u, int p = -1, int depth = 1)
{
if(sum > k) return;
if(filling)
minimize(cnt[sum], depth);
else {
if(cnt[k - sum] != -1)
minimize(ans, depth + cnt[k - sum]);
}
for(auto [C, v]: adj[u]) {
if(v != p && !r[v]) get_cnt(sum + C, filling, v, u, depth + 1);
}
}
void del(int sum, int u, int p = -1)
{
if(sum > k) return;
cnt[sum] = -1;
for(auto [C, v]: adj[u]) {
if(v != p && !r[v])
del(sum + C, v, u);
}
}
void centroid(int u = 0)
{
u = get_centroid(dfs(u), u);
r[u] = 1;
cnt[0] = 0;
for(auto [C, v]: adj[u]) {
if(!r[v]) {
get_cnt(C, false, v);
get_cnt(C, true, v);
}
}
for(auto [C, v]: adj[u]) {
if(!r[v]) {
del(C, v);
}
}
for(auto [C, v]: adj[u]) {
if(!r[v]) centroid(v);
}
}
int best_path(int N, int K, int h[][2], int L[])
{
n = N;
k = K;
for(int i = 0, u, v; i < n - 1; ++i) {
u = h[i][0];
v = h[i][1];
adj[u].push_back(ii(L[i], v));
adj[v].push_back(ii(L[i], u));
}
ans = -1;
memset(cnt, -1, sizeof(cnt));
centroid();
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... |