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>
#include "race.h"
using namespace std;
const int N = 2e5 + 10;
int total_sz, wei, answer;
bool marked[N];
int sz[N];
vector<pair<int, int>> ad[N];
void dfs1(int u, int p) {
sz[u] = 1;
total_sz += 1;
for (const auto& [v, w] : ad[u]) {
if (marked[v] || v == p) continue;
dfs1(v, u);
sz[u] += sz[v];
}
}
int dfs2(int u, int p) {
for (const auto& [v, w] : ad[u]) {
if (marked[v] || v == p) continue;
if (sz[v] > total_sz / 2) return dfs2(v, u);
}
return u;
}
int f[N];
vector<int> undo;
vector<pair<int, int>> lst;
void dfs3(int u, int p, int d, int tw) {
lst.push_back({d, tw});
undo.push_back(d);
for (const auto& [v, w] : ad[u]) {
if (v == p || marked[v]) continue;
dfs3(v, u, d + 1, tw + w);
}
}
void dfs4(int u) {
total_sz = 0;
dfs1(u, -1);
marked[u = dfs2(u, -1)] = true;
f[0] = 0;
for (const auto& [v, w] : ad[u]) {
dfs3(v, u, 1, w);
for (const auto& [d, tw] : lst) {
if (tw > wei) continue;
answer = min(answer, d + f[wei - tw]);
}
for (const auto& [d, tw] : lst) {
if (tw > wei) continue;
f[d] = min(f[d], tw);
}
lst.clear();
}
for (const auto& i : undo) f[i] = 1e7;
undo.clear();
for (const auto& [v, w] : ad[u]) {
if (marked[v]) continue;
dfs4(v);
}
}
int best_path(int n, int k, int h[][2], int l[]) {
for (int i = 0; i < n - 1; ++i) {
int u = h[i][0], v = h[i][1], w = l[i];
ad[u].push_back({v, w});
ad[v].push_back({u, w});
}
answer = 1e7; wei = k;
memset(f, 40, sizeof f);
dfs4(0);
return answer > n ? -1 : answer;
}
#ifdef LOCAL
#define MAX_AA 500000
static int AA, K;
static int H[MAX_AA][2];
static int L[MAX_AA];
static int solution;
#define int long long
mt19937_64 rng(8384815663);
int rnd(int l, int r) { return l + rng() % (r - l + 1); }
inline
void my_assert(int e) {if (!e) abort();}
void read_input()
{
freopen("input.txt", "r", stdin);
// AA = rnd(2e5, 2e5), K = rnd(100, 100);
cin >> AA >> K;
for (int i = 0; i < AA - 1; ++i) {
// H[i][0] = rnd(i, i);
// H[i][1] = i + 1;
// L[i] = rnd(1, 100);
cin >> H[i][0] >> H[i][1];
cin >> L[i];
}
solution = -1;
// cin >> solution;
}
int32_t main() {
int ans;
read_input();
ans = best_path(AA,K,H,L);
cout << ans << "\n";
return 0;
}
#endif
# | 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... |