이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
#define F first
#define S second
#define eb emplace_back
#define bit(x, i) (((x) >> (i)) & 1)
using namespace std;
using ll = long long;
const int inf = 1061109567;
const ll INF = 4557430888798830399;
const int MOD = 998244353;
int n, lenRace;
vector <pair <int, int>> adj[200005];
int subtree_size[200005];
int minDepth[1000005];
bool vis[200005];
int res = inf;
int dfs(int u, int par) {
int &ret = subtree_size[u];
ret = 1;
for (auto pii : adj[u]) {
int v = pii.F;
if (v != par && !vis[v])
ret += dfs(v, u);
}
return ret;
}
int find_centroid(int u, int par, int sz) {
for (auto pii : adj[u]) {
int v = pii.F;
if (v != par && !vis[v] && subtree_size[v] * 2 > sz)
return find_centroid(v, u, sz);
}
return u;
}
void calc(int u, int par, int sign, int depth, int len) {
if (len > lenRace)
return;
if (sign == 0)
res = min(res, depth + minDepth[lenRace-len]);
else if (sign == 1)
minDepth[len] = min(minDepth[len], depth);
else
minDepth[len] = inf;
for (auto pii : adj[u]) {
int v = pii.F;
int w = pii.S;
if (!vis[v] && v != par)
calc(v, u, sign, depth + 1, len + w);
}
}
void process(int u, int par) {
int centroid = find_centroid(u, -1, dfs(u, -1));
vis[centroid] = true;
for (auto pii : adj[centroid]) {
int v = pii.F, w = pii.S;
if (vis[v])
continue;
calc(v, centroid, 0, 1, w);
calc(v, centroid, 1, 1, w);
}
for (auto pii : adj[centroid]) {
int v = pii.F;
int w = pii.S;
if (!vis[v])
continue;
calc(v, centroid, -1, 1, w);
}
}
int best_path(int N, int K, int h[][2], int L[]) {
n = N;
lenRace = K;
for (int i = 1; i < n; ++ i) {
int u = h[i][0] + 1;
int v = h[i][1] + 1;
adj[u].eb(v, L[i]);
adj[v].eb(u, L[i]);
}
for (int i = 1; i <= 1e6; ++ i)
minDepth[i] = inf;
process(1, -1);
if (res == inf)
res = -1;
return res;
}
//
//int32_t main(void) {
// cin.tie(0)->sync_with_stdio(0);
// if (fopen(".in", "r")) {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
// }
// cin >> n >> lenRace;
// for (int i = 1; i < n; ++ i) {
// int u, v, w; cin >> u >> v >> w;
// ++ u, ++ v;
// adj[u].eb(v, w);
// adj[v].eb(u, w);
// }
// for (int i = 1; i <= 1e6; ++ i)
// minDepth[i] = inf;
// process(1, -1);
// cout << res;
// return 0;
//}
// Written by Kazama Hoang ^^
# | 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... |