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>
using namespace std;
using ll = long long;
using ld = long double;
using str = string;
using pi = pair<int, int>;
using pl = pair<ll, ll>;
using pd = pair<ld, ld>;
#define mp make_pair
#define ff first
#define ss second
template<class T> using V = vector<T>;
#define arr array
using vi = V<int>;
using vb = V<bool>;
using vl = V<ll>;
using vd = V<ld>;
using vs = V<str>;
using vpi = V<pi>;
using vpl = V<pl>;
using vpd = V<pd>;
#define sz(x) (int)((x).size())
#define bg(x) begin(x)
#define all(x) bg(x), end(x)
#define rall(x) (x).rbegin(), (x).rend()
#define sor(x) sort(all(x))
#define rsz resize
#define ins insert
#define pb push_back
#define eb emplace_back
#define ft front()
#define bk back()
#define lb lower_bound
#define ub upper_bound
#define FOR(i, a, b) for(int i = (a); i < (b); ++i)
#define F0R(i, a) FOR(i, 0, a)
#define ROF(i, a, b) for(int i = (b) - 1; i >= (a); --i)
#define R0F(i, a) ROF(i, 0, a)
#define rep(a) F0R(_, a)
#define trav(a, x) for(auto& a : x)
template<class T> bool ckmin(T& a, const T& b) { return (b < a ? a = b, 1 : 0); }
template<class T> bool ckmax(T& a, const T& b) { return (b > a ? a = b, 1 : 0); }
int N, K, ans;
vi ssz, kp;
vb vis;
V<vpi> adj;
int dfs0(int s, int p = -1) {
ssz[s] = 1;
trav(u, adj[s]) {
if(u.ff != p && !vis[u.ff]) ssz[s] += dfs0(u.ff, s);
}
return ssz[s];
}
int cent(int s, int des, int p = -1) {
trav(u, adj[s]) {
if(u.ff != p && !vis[u.ff] && 2 * ssz[u.ff] > des) return cent(u.ff, des, s);
}
return s;
}
void dfs1(int s, pi D, int c, int p = -1) {
if(D.ff > K) return;
if(c == 0) {
ckmin(ans, D.ss + kp[K - D.ff]);
} else if(c == 1) {
ckmin(kp[D.ff], D.ss);
} else {
kp[D.ff] = 0x3f3f3f3f;
}
trav(u, adj[s]) {
if(u.ff != p && !vis[u.ff]) dfs1(u.ff, mp(D.ff + u.ss, D.ss + 1), c, s);
}
}
void cent_deco(int s = 0) {
s = cent(s, dfs0(s));
vis[s] = 1;
kp[0] = 0;
trav(u, adj[s]) {
if(vis[u.ff]) continue;
dfs1(u.ff, mp(u.ss, 1), 0);
dfs1(u.ff, mp(u.ss, 1), 1);
}
trav(u, adj[s]) {
if(vis[u.ff]) continue;
dfs1(u.ff, mp(u.ss, 1), 2);
}
trav(u, adj[s]) {
if(vis[u.ff]) continue;
cent_deco(u.ff);
}
}
int best_path(int _N, int _K, int e[][2], int w[]) {
N = _N; K = _K;
vis.rsz(N);
adj.rsz(N);
ssz.rsz(N);
ans = 0x3f3f3f3f;
kp = vi(K + 1, ans);
F0R(i, N - 1) {
adj[e[i][0]].eb(e[i][1], w[i]);
adj[e[i][1]].eb(e[i][0], w[i]);
}
cent_deco();
if(ans == 0x3f3f3f3f) ans = -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... |