이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5 + 7;
const int K = 1e6 + 7;
const int LG = 20;
const int inf = 1e9 + 7;
int n, k;
int sz[N];
bool used[N];
vector <pair <int, int> > g[N];
vector <int> go(K, inf);
int ans = inf;
void calc(int v, int pr) {
sz[v] = 1;
for (auto to : g[v]) {
if (to.first != pr && !used[to.first]) {
calc(to.first, v);
sz[v] += sz[to.first];
}
}
}
int centroid(int v, int pr, int need) {
for (auto to : g[v]) {
if (to.first != pr && !used[to.first] && sz[to.first] > need / 2) {
return centroid(to.first, v, need);
}
}
return v;
}
void dfs(int v, int pr, int h, int cur) {
if (cur > k) {
return;
}
go[cur] = min(go[cur], h);
for (auto to : g[v]) {
if (to.first != pr && !used[to.first]) {
dfs(to.first, v, h + 1, cur + to.second);
}
}
}
void build(int v, int lg) {
calc(v, -1);
v = centroid(v, -1, sz[v]);
vector <int> dp(k + 1, inf);
dp[0] = 0;
for (auto to : g[v]) {
if (!used[to.first]) {
for (int i = 0; i <= k; i++) {
go[i] = inf;
}
go[0] = 0;
dfs(to.first, v, 1, to.second);
for (int i = 0; i <= k; i++) {
ans = min(ans, go[i] + dp[k - i]);
}
for (int i = 0; i <= k; i++) {
dp[i] = min(dp[i], go[i]);
}
}
}
used[v] = true;
for (auto to : g[v]) {
if (!used[to.first]) {
build(to.first, lg + 1);
}
}
}
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, v, l;
u = H[i][0];
v = H[i][1];
l = L[i];
g[u].push_back({v, l});
g[v].push_back({u, l});
}
build(0, 0);
return (ans == inf ? -1 : 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... |