이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
int ans = INT_MAX;
int sz[200005];
vector<pair<int, int>> adj[200005];
bool removed[200005];
void dfssz(int v, int par = -1) {
sz[v] = 1;
for (auto u : adj[v]) {
if (u.first == par) continue;
if (removed[u.first]) continue;
dfssz(u.first, v);
sz[v] += sz[u.first];
}
}
int centroid(int v, int full, int par = -1) {
for (auto u : adj[v]) {
if (u.first == par) continue;
if (removed[u.first]) continue;
if (sz[u.first] * 2 > full) {
return centroid(u.first, full, v);
}
}
return v;
}
void update(map<int, int>& mp, map<int, int>& mp2, int len, int val, int K) {
if (mp2.find(len) == mp2.end()) mp2[len] = val;
else mp2[len] = min(mp2[len], val);
if (mp.find(K - len) != mp.end()) ans = min(ans, mp2[len] + mp[K - len]);
}
void solve(int v, map<int, int> &mp, map<int, int> &mp2, int len, int K, int depth, int par) {
for (auto u : adj[v]) {
if (u.first == par) continue;
if (removed[u.first]) continue;
if (len + u.second <= K) {
update(mp, mp2, len + u.second, 1 + depth, K);
solve(u.first, mp, mp2, len + u.second, K, depth + 1, v);
}
}
}
void decompose(int v, int K) {
dfssz(v);
int c = centroid(v, sz[v]);
map<int, int> mp;
for (auto u : adj[c]) {
if (removed[u.first]) continue;
if (u.second > K) continue;
map<int, int> mp2;
update(mp, mp2, u.second, 1, K);
solve(u.first, mp, mp2, u.second, K, 1, c);
for (auto it : mp2) {
if (mp.find(it.first) != mp.end()) mp[it.first] = min(mp[it.first], it.second);
else mp[it.first] = it.second;
}
}
if (mp.find(K) != mp.end()) ans = min(ans, mp[K]);
removed[c] = 1;
for (auto u : adj[c]) {
if (removed[u.first]) continue;
decompose(u.first, K);
}
}
int best_path(int N, int K, int H[][2], int L[]) {
for (int i = 0; i < N - 1; i++) {
int u = H[i][0], v = H[i][1];
adj[u].push_back({v, L[i]});
adj[v].push_back({u, L[i]});
}
decompose(0, K);
if (ans != INT_MAX) return ans;
return -1;
}
# | 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... |