This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#pragma GCC optimize("O3")
#include <bits/stdc++.h>
using namespace std;
#define all(arr) (arr).begin(), (arr).end()
#define ll long long
#define ld long double
#define pb push_back
#define sz(x) int((x).size())
#define fi first
#define se second
#define endl '\n'
const int N = 2e5 + 20, INF = 1e9;
vector<pair<int, int>> g[N];
map<ll, ll> min_edges[N];
ll delta_length[N], delta_cnt[N];
ll ans = INF, K;
void dfs(int v, int p){
int maxguy = -1, maxw;
for (auto [u, w] : g[v]){
if (u == p) continue;
dfs(u, v);
if (maxguy == -1 || sz(min_edges[maxguy]) < sz(min_edges[u])) maxguy = u, maxw = w;
}
if (maxguy != -1){
min_edges[v] = move(min_edges[maxguy]), delta_length[v] = delta_length[maxguy] + maxw,
delta_cnt[v] = delta_cnt[maxguy] + 1;
}
for (auto [u, w] : g[v]){
if (u == p) continue;
if (u != maxguy){
for (auto [len, cnt] : min_edges[u]){
ll len1 = len + delta_length[u] + w - delta_length[v];
ll cnt1 = cnt + delta_cnt[u] + 1 - delta_cnt[v];
if (min_edges[v].count(K - len1 - 2 * delta_length[v])){
ans = min(ans, cnt1 + 2 * delta_cnt[v] + min_edges[v][K - len1 - 2 * delta_length[v]]);
}
if (min_edges[v].count(len1)) min_edges[v][len1] = min(min_edges[v][len1], cnt1);
else min_edges[v][len1] = cnt1;
}
min_edges[u].clear();
}
}
min_edges[v][-delta_length[v]] = -delta_cnt[v];
if (min_edges[v].count(K - delta_length[v])) ans = min(ans, min_edges[v][K - delta_length[v]] + delta_cnt[v]);
}
int best_path(int n, int k, int h[][2], int l[]){
for (int i = 0; i < n; i++){
g[i].clear();
min_edges[i].clear();
delta_length[i] = delta_cnt[i] = 0;
}
K = k, ans = INF;
for (int i = 0; i < n - 1; i++){
g[h[i][0]].pb({h[i][1], l[i]});
g[h[i][1]].pb({h[i][0], l[i]});
}
dfs(0, 0);
return ans == INF? -1 : ans;
}
// signed main(){
// ios_base::sync_with_stdio(0);
// cin.tie(0);
// // cout.precision(20);
// int n, k;
// cin >> n >> k;
// int h[n - 1][2], l[n - 1];
// for (int i = 0; i < n - 1; i++){
// cin >> h[i][0] >> h[i][1];
// }
// for (int i = 0; i < n - 1; i++){
// cin >> l[i];
// }
// cout << best_path(n, k, h, l) << endl;
// }
# | 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... |