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>
#ifndef EVAL
#include "grader.cpp"
#endif
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
#define pb push_back
#define mp make_pair
#define all(v) (v).begin(),(v).end()
#define sz(v) int((v).size())
#define do_not_disturb ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
int mod = 1e9+7;
ll modulo(ll a) {
return ((a % mod) + mod) % mod;
}
ll add(ll a, ll b) {
return modulo(a + b);
}
ll mult(ll a, ll b) {
return modulo(a * b);
}
ll binpow(ll a, ll b) {
ll res = 1;
while (b) {
if (b&1) {
res = mult(res, a);
}
a = mult(a, a);
b >>= 1;
}
return res;
}
const int MAXN = 2e5+7;
vector <pll> graph[MAXN];
ll ans = 9e18;
multiset <pll> paths;
ll n, KK;
int used[MAXN], subtree[MAXN];
void dfs(int v, int p) {
subtree[v] = 1;
for (auto to : graph[v]) {
if (used[to.first] || to.first == p) continue;
dfs(to.first, v);
subtree[v] += subtree[to.first];
}
}
int find_centroid(int v, int p, int saizu) {
for (auto to : graph[v]) {
if (used[to.first] || to.first == p) continue;
if (subtree[to.first] * 2 > saizu) {
return find_centroid(to.first, v, saizu);
}
}
return v;
}
void get_paths(int v, int p, ll dist, int len, bool flag) {
if (flag) {
paths.insert(mp(dist, len));
}
else {
paths.erase(paths.find(mp(dist, len)));
}
for (auto to : graph[v]) {
if (used[to.first] || to.first == p) continue;
get_paths(to.first, v, dist+to.second, len+1, flag);
}
}
void calculate(int v, int p, ll dist, int len) {
auto it = paths.lower_bound(mp(KK-dist, 0));
if (it != paths.end() && (*it).first == KK-dist) {
ans = min(ans, len+(*it).second);
}
for (auto to : graph[v]) {
if (used[to.first] || to.first == p) {
continue;
}
calculate(to.first, v, dist+to.second, len+1);
}
}
void centroid_decomposition(int v) {
dfs(v, v);
auto centroid = find_centroid(v, v, subtree[v]);
used[centroid] = 1;
get_paths(centroid, centroid, 0, 0, 1);
for (auto to : graph[centroid]) {
if (used[to.first]) continue;
get_paths(to.first, centroid, to.second, 1, 0);
calculate(to.first, to.first, to.second, 1);
get_paths(to.first, centroid, to.second, 1, 1);
}
get_paths(centroid, centroid, 0, 0, 0);
for (auto to : graph[centroid]) {
if (!used[to.first]) {
centroid_decomposition(to.first);
}
}
}
int best_path(int N, int k, int h[][2], int l[]) {
n = N;
KK = k;
for (int i = 0; i < n-1; i++) {
graph[h[i][0]].pb(mp(h[i][1], l[i]));
graph[h[i][1]].pb(mp(h[i][0], l[i]));
}
centroid_decomposition(1);
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... |