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"
#define mp make_pair
#define pb push_back
#define pii pair<int, int>
#define nyan "(=^・ω・^=)"
#define read_input freopen("in.txt","r", stdin)
#define print_output freopen("out.txt","w", stdout)
typedef long long ll;
typedef long double ld;
using namespace std;
const int maxn = 2e5+10;
const int inf = 1e6+13;
int sz[maxn], lev[maxn], dist[maxn];
int in[maxn], out[maxn], ver[maxn];
unordered_map<ll, int> M;
int idx = 1, n, k;
vector<pii> adj[maxn];
void getsz(int u, int par) {
ver[idx] = u; in[u] = idx++;
sz[u] = 1; lev[u] = lev[par] + 1;
for(auto p : adj[u]) {
int v = p.first; ll w = p.second;
if(v == par) continue;
dist[v] = dist[u] + w;
getsz(v, u);
sz[u] += sz[v];
} out[u] = idx;
}
int ans = inf;
void dfs(int u, int par, int keep) {
int mx = -1, bigchild = -1;
for(auto v : adj[u]) {
if(v.first == par) continue;
if(sz[v.first] > mx) mx = sz[v.first], bigchild = v.first;
}
for(auto v : adj[u]) {
if(v.first == par || v.first == bigchild) continue;
dfs(v.first, u, 0);
}
M[dist[u]] = u;
if(bigchild != -1) {
dfs(bigchild, u, 1);
ll w = k + dist[u];
if(M.find(w) != M.end())
ans = min(ans, lev[M[w]] - lev[u]);
}
for(auto v : adj[u]) {
if(v.first == par || v.first == bigchild) continue;
int x = v.first;
for(int p = in[x]; p < out[x]; p++) {
ll w = k + 2LL * dist[u] - dist[ver[p]];
if(M.find(w) != M.end())
ans = min(ans, lev[M[w]] + lev[ver[p]] - 2*lev[u]);
}
for(int p = in[x]; p < out[x]; p++) {
int x = ver[p]; ll w = dist[x];
if(M.find(w) == M.end() || lev[x] < lev[M[w]]) M[w] = x;
}
}
if(not keep)
M.clear();
}
int best_path(int N, int K, int H[][2], int L[]) {
n = N; k = K;
for (int i = 0; i < n-1; i++){
adj[H[i][0]].emplace_back(H[i][1], L[i]);
adj[H[i][1]].emplace_back(H[i][0], L[i]);
}
getsz(0, -1);
dfs(0, -1, 0);
if (ans == inf) return -1;
return 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... |