# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1083904 | sonho00 | Race (IOI11_race) | C++17 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
#define int long long
using namespace std;
struct CD {
int n;
vector<vector<int>> adj, tree;
vector<int> sz;
vector<bool> used;
CD(int n) : n(n), adj(n + 1), tree(n + 1), sz(n + 1), used(n + 1) {}
int getSz(int cur, int par) {
sz[cur] = 1;
for (int nei : adj[cur]) {
if (used[nei] || nei == par) continue;
sz[cur] += getSz(nei, cur);
}
return sz[cur];
}
int getCent(int cur, int tot, int par) {
for (int nei : adj[cur]) {
if (used[nei] || nei == par) continue;
if (tot < sz[nei] * 2) return getCent(nei, tot, cur);
}
return cur;
}
int getRoot(int cur = 1) {
cur = getCent(cur, getSz(cur, -1), -1);
used[cur] = 1;
for (int nei : adj[cur]) {
if (used[nei]) continue;
tree[cur].push_back(getRoot(nei));
}
return cur;
}
};
signed f() {
cin.tie(0)->sync_with_stdio(0);
int n, k;
cin >> n >> k;
CD cd(n);
vector<vector<pair<int, int>>> adj(n);
for (int i = 1; i < n; ++i) {
int u, v, w;
cin >> u >> v >> w;
cd.adj[u].push_back(v);
cd.adj[v].push_back(u);
adj[u].emplace_back(w, v);
adj[v].emplace_back(w, u);
}
vector<bool> used(n);
vector<int> dp(k+1, n);
int ans = n;
function<void(int, int, int, int, int)> dfs =
[&](int cur, int par, int dist, int dep, int type) {
if (dist > k) return;
if (type == 1) ans = min(ans, dep + dp[k - dist]);
if (type == 2) dp[dist] = min(dp[dist], dep);
if (type == 3) dp[dist] = n;
for (auto &[wei, nei] : adj[cur]) {
if (used[nei] || nei == par) continue;
dfs(nei, cur, dist + wei, dep + 1, type);
}
};
function<void(int)> solve = [&](int root) {
used[root] = 1;
dp[0] = 0;
for (auto &[wei, nei] : adj[root]) {
if (used[nei]) continue;
dfs(root, -1, 0, 0, 1);
dfs(root, -1, 0, 0, 2);
}
for (auto &[wei, nei] : adj[root]) {
if (used[nei]) continue;
dfs(root, -1, 0, 0, 3);
}
for (int nei : cd.tree[root]) {
if (used[nei]) continue;
solve(nei);
}
};
solve(cd.getRoot(0));
if (ans == n) ans = -1;
return ans;
}