이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <queue>
#include <set>
#include <map>
#define INF 1e9
using namespace std;
typedef long long ll;
int n, k;
ll ans = INF;
vector<pair<int, int>>adj[200005];
bool visited[200005];
ll dp[200005];
map<ll,ll>seen;
vector<ll>v;
int get_size(int s, int e) {
dp[s] = 1;
for (auto u : adj[s]) {
if (u.first == e || visited[u.first]) continue;
get_size(u.first, s);
dp[s] += dp[u.first];
}
return dp[s];
}
int get_centroid(int s, int e, int n) {
for (auto u : adj[s]) {
if (u.first == e || visited[u.first]) continue;
if (dp[u.first] * 2 > n)return get_centroid(u.first, s, n);
}
return s;
}
void dfs(int s, int e, bool flag, int sum, ll dep = 1) {
if (!flag) {
if (seen.find(k - sum) != seen.end()) ans = min(ans, seen[k - sum] + dep);
}
else {
if (seen.find(sum) == seen.end())seen[sum] = dep;
else seen[sum] = min(seen[sum], dep);
}
for (auto u : adj[s]) {
if (u.first == e || visited[u.first]) continue;
dfs(u.first, s, flag, sum + u.second, dep + 1);
}
}
void centroid_decomposition(int node) {
int centroid = get_centroid(node, 0, get_size(node, 0));
visited[centroid] = true;
seen.clear();
for (auto u : adj[centroid]) {
if (!visited[u.first]) {
dfs(u.first, centroid, false, u.second);
dfs(u.first, centroid, true, u.second);
}
}
if (seen.find(k) != seen.end()) ans = min(ans, seen[k]);
for (auto u : adj[centroid]) {
if (!visited[u.first])centroid_decomposition(u.first);
}
}
int best_path(int N, int K, int H[][2], int L[]) {
n = N; k = K;
for (int i = 1; i <= N - 1; i++) {
adj[H[i][0]].push_back({ H[i][1],L[i] });
adj[H[i][1]].push_back({ H[i][0],L[i] });
}
centroid_decomposition(1);
if (ans == INF) return -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... |