이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include "race.h"
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define ar array
const int INF = 1e9;
const int MOD = 1e9 + 7;
int OneCentroid(int rt, vector<vector<ar<int,2>>> &g, vector<bool> &dead) {
int n = g.size();
vector<int> sz(n);
function<void(int,int)> get_sz = [&](int u, int pu) {
sz[u] = 1;
for (auto v : g[u]) if (v[1] != pu && !dead[v[1]]) {
get_sz(v[1], u);
sz[u] += sz[v[1]];
}
};
get_sz(rt, rt);
function<int(int,int)> dfs = [&](int u, int pu) {
for (auto v : g[u]) if (v[1] != pu && !dead[v[1]]) {
if (sz[v[1]] > sz[rt]/2) return dfs(v[1], u);
}
return u;
};
return dfs(rt, rt);
}
int CentroidDecomposition(vector<vector<ar<int,2>>> &g, int k) {
int n = g.size();
vector<bool> dead(n, false);
vector<int> length(k+1, INF), lastcnt(k+1, -1);
vector<ar<int,2>> to_update;
int ans = INT_MAX; int cnt = 0;
function<void(int,int,int,int)> dfs = [&](int u, int pu, int len, int dist) {
if (k < dist || len > ans) return;
if (k-dist >= 0 && lastcnt[k-dist] == cnt)
ans = min(ans, length[k-dist] + len);
to_update.push_back({dist, len});
for (auto v : g[u]) if (v[1] != pu && !dead[v[1]])
dfs(v[1], u, len + 1, dist + v[0]);
};
function<void(int)> decompose = [&](int start) {
int cen = OneCentroid(start, g, dead);
length[0] = 0; lastcnt[0] = ++cnt;
// do stuff with subtree of centroid here
// get length, distance to each node in subtree of centroid from centroid
// ans = min(ans, length) if distance corresponding to it is k
for (auto v : g[cen]) if (!dead[v[1]]) {
dfs(v[1], cen, 1, v[0]);
for (auto x : to_update) if (x[0] <= k) {
if (lastcnt[x[0]] != cnt || length[x[0]] > x[1]) length[x[0]] = x[1];
lastcnt[x[0]] = cnt;
}
to_update.clear();
}
dead[cen] = true;
for (auto v : g[cen]) if (!dead[v[1]]) decompose(v[1]);
dead[cen] = false;
};
decompose(0);
return (ans < INF/2) ? ans : -1;
}
int best_path(int N, int K, int H[][2], int L[]) {
vector<vector<ar<int,2>>> g(N);
for (int i = 0; i < N-1; i++) {
g[H[i][0]].push_back({L[i], H[i][1]});
g[H[i][1]].push_back({L[i], H[i][0]});
}
return CentroidDecomposition(g, K);
}
# | 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... |