#include <bits/stdc++.h>
using namespace std;
vector<pair<int,int> > G[200005];
bool is_removed[200005];
int subtree_size[200005];
int rez=INT_MAX;
int cekori[1000005];
int k;
int get_subtree_size(int teme, int parent=-1) {
subtree_size[teme]=1;
for (auto [next, dolz]:G[teme]) {
if (next==parent||is_removed[next]) continue;
subtree_size[teme]+=get_subtree_size(next, teme);
}
return subtree_size[teme];
}
int get_centroid(int teme, int tree_size, int parent=-1) {
for (auto [next, dolz]:G[teme]) {
if (next==parent||is_removed[next]) continue;
if (subtree_size[next]*2>tree_size)
return get_centroid(next, tree_size, teme);
}
return teme;
}
queue<int> q;
void dfs2(int teme, int parent=-1, int dolz=0, int depth=0) {
if (dolz>=k) {
if (dolz==k) rez=min(rez, depth);
return;
}
if (cekori[dolz]>depth) cekori[dolz]=depth;
else if (cekori[dolz]==-1) cekori[dolz]=depth, q.push(dolz);
if (cekori[k-dolz]!=-1)
rez=min(rez, cekori[k-dolz]+depth);
for (auto [next, dist]:G[teme]) {
if (next==parent||is_removed[next]) continue;
dfs2(next, teme, dolz+dist, depth+1);
}
}
void build_centroid_decomp(int teme=0) {
int centroid=get_centroid(teme, get_subtree_size(teme));
dfs2(centroid);
while (!q.empty()) {
int br=q.front();
q.pop();
cekori[br]=-1;
}
is_removed[centroid]=1;
for (auto [next, dist]:G[centroid]) {
if (is_removed[next]) continue;
build_centroid_decomp(next);
}
}
int best_path(int n, int K, int H[][2], int L[]) {
for (int i=0;i<n-1;i++) {
G[H[i][0]].push_back({H[i][1], L[i]});
G[H[i][1]].push_back({H[i][0], L[i]});
}
k=K;
memset(cekori, -1, sizeof(cekori));
build_centroid_decomp();
if (rez==INT_MAX) return -1;
return rez;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
2 ms |
12888 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
2 ms |
12888 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
2 ms |
12888 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
2 ms |
12888 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |