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 <iostream>
#include <vector>
using namespace std;
const int NMAX = 1e5;
const int KMAX = 1e6;
vector<pair<int, int>> g[NMAX];
int w[NMAX];
bool used[NMAX];
int minLength[KMAX + 1];
int Ans;
int get_w(int node, int dad = -1) {
w[node] = 1;
for (auto it : g[node]) {
if (it.first == dad || used[it.first]) continue;
get_w(it.first, node);
w[node] += w[it.first];
}
return w[node];
}
int get_centroid(int node, int totalW, int dad = -1) {
for (auto it : g[node]) {
if (it.first == dad || used[it.first]) continue;
if (w[it.first] > totalW / 2)
return get_centroid(it.first, node);
}
return node;
}
void dfs_add(int node, int k, int length = 0, int dad = -1, int depth = 0) {
if (length > k) return;
minLength[length] = min(minLength[length], depth);
for (auto it : g[node]) {
if (it.first == dad || used[it.first]) continue;
dfs_add(it.first, k, length + it.second, node, depth + 1);
}
}
void dfs_compute(int node, int k, int length = 0, int dad = -1) {
if (length > k) return;
Ans = min(Ans, minLength[length] + minLength[k - length]);
for (auto it : g[node]) {
if (it.first == dad || used[it.first]) continue;
dfs_compute(it.first, k, length + it.second, node);
}
}
void dfs_clear(int node, int k, int length = 0, int dad = -1) {
if (length > k) return;
minLength[length] = NMAX;
for (auto it : g[node]) {
if (it.first == dad || used[it.first]) continue;
dfs_clear(it.first, k, length + it.second, node);
}
}
void go(int node, int k) {
int totalW = get_w(node);
int c = get_centroid(node, totalW);
used[c] = true;
dfs_add(c, k);
dfs_compute(c, k);
dfs_clear(c, k);
for (auto it : g[c])
if (!used[it.first])
go(it.first, k);
}
int best_path(int N, int K, int H[][2], int L[]) {
Ans = N;
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]);
}
go(0, K);
return Ans == N ? -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... |