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>
#define pii pair<int, int>
#define x first
#define y second
using namespace std;
const int N = 2e5 + 5;
const int M = 1e6 + 5;
int n, k, ans = -1;
int sub[N];
int dp[M], tim[M];
vector<pii> g[N];
int getsz(int u, int p) {
sub[u] = 1;
for(pii v : g[u]) if(v.x != p) sub[u] += getsz(v.x, u);
return sub[u];
}
void add(int u, int p, int cost, int len, int cnt) {
if(cost > k) return;
if(tim[k - cost] == cnt && (ans == -1 || len + dp[k - cost] < ans)) ans = len + dp[k - cost];
if(cost == k && (ans == -1 || len < ans)) ans = len;
for(pii v : g[u]) if(v.x != p) add(v.x, u, cost + v.y, len + 1, cnt);
}
void prep(int u, int p, int cost, int len, int cnt) {
if(cost > k) return;
if(tim[cost] != cnt || len < dp[cost]) tim[cost] = cnt, dp[cost] = len;
for(pii v : g[u]) if(v.x != p) prep(v.x, u, cost + v.y, len + 1, cnt);
}
void dfs(int u, int p, bool keep, int cost) {
int mx = 0, hv, hve;
for(pii v : g[u]) if(v.x != p && mx < sub[v.x]) mx = sub[v.x], hv = v.x, hve = v.y;
for(pii v : g[u]) if(v.x != p && v.x != hv) dfs(v.x, u, 0, v.y);
if(mx) dfs(hv, u, 1, hve);
for(pii v : g[u]) if(v.x != p && v.x != hv) {
add(v.x, u, v.y, 1, u);
prep(v.x, u, v.y, 1, u);
}
if(tim[k] == u && (ans == -1 || dp[k] < ans)) ans = dp[k];
/*printf("%d: ", u);
for(int i = 1; i <= k + 1; i++) {if(tim[i] == u) printf("%d ", dp[i]); else printf("X ");}
printf("\n");*/
if(keep) prep(u, p, cost, 1, p);
}
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]);
}
fill(begin(tim), end(tim), -1);
getsz(0, 0);
dfs(0, 0, 1, 0);
return ans;
}
/*int main() {
scanf("%d%d", &n, &k);
for(int i = 1, u, v, w; i <= n; i++) {
scanf("%d%d%d", &u, &v, &w);
g[u].emplace_back(v, w);
g[v].emplace_back(u, w);
}
fill(begin(tim), end(tim), -1);
getsz(0, 0);
dfs(0, 0, 1, 0);
printf("%d", ans);
return 0;
}*/
Compilation message (stderr)
race.cpp: In function 'void dfs(int, int, bool, int)':
race.cpp:40:32: warning: 'hv' may be used uninitialized in this function [-Wmaybe-uninitialized]
for(pii v : g[u]) if(v.x != p && v.x != hv) dfs(v.x, u, 0, v.y);
~~~~~~~~~^~~~~~~~~~~~
# | 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... |