This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
// In the name of the God
#include <bits/stdc++.h>
#define ll long long
// #define int long long
#define pb push_back
#define F first
#define S second
#define mp make_pair
#define pii pair <int, int>
#define smin(x, y) (x) = min((x), (y))
#define smax(x, y) (x) = max((x), (y))
#define all(x) (x).begin(), (x).end()
using namespace std;
const int inf = 1e9+7;
const int mod = 998244353;
const int maxn = 2e5+5, maxk = 1e6+5;
int n, k, ans = inf, sz[maxn], mn[maxk];
bool mark[maxn];
vector <pii> adj[maxn], vec1;
vector <int> vec2;
void dfs1(int v, int p) {
sz[v] = 1;
for (pii e : adj[v]) {
int u = e.F;
if (u != p and !mark[u]) {
dfs1(u, v); sz[v] += sz[u];
}
}
}
int dfs2(int v, int s, int p) {
for (pii e : adj[v]) {
int u = e.F;
if (u != p and !mark[u] and sz[u] > s/2) return dfs2(u, s, v);
}
return v;
}
void dfs3(int v, int c, int h, int p) {
if (c > k) return;
vec2.pb(c); vec1.pb(mp(c, h));
smin(ans, mn[k-c]+h);
for (pii e : adj[v]) {
int u = e.F;
if (u != p and !mark[u]) dfs3(u, c+e.S, h+1, v);
}
}
void cd(int v) {
dfs1(v, v);
v = dfs2(v, sz[v], v);
mn[0] = 0; vec2.pb(0);
for (pii e : adj[v]) {
int u = e.F;
if (!mark[u]) {
dfs3(u, e.S, 1, v);
for (pii x : vec1) smin(mn[x.F], x.S);
vec1.clear();
}
}
for (int x : vec2) mn[x] = inf;
vec2.clear();
mark[v] = 1;
for (pii e : adj[v]) {
int u = e.F;
if (!mark[u]) cd(u);
}
}
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]].pb(mp(H[i][1], L[i]));
adj[H[i][1]].pb(mp(H[i][0], L[i]));
}
fill(mn, mn+maxk, inf);
cd(0);
return ans == inf ? -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... |