This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <queue>
#include <set>
#include <map>
#define INF 1e9
using namespace std;
typedef long long ll;
const int MAX = 1e6 + 5;
int n, k, ans = INF, dp[MAX];
vector<int>cnt(MAX, INF);
bool visited[MAX];
vector<int>v;
vector<pair<int, int>>adj[MAX];
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, int dep) {
if (sum > k)return;
if (!flag) {
ll need = k - sum;
if (cnt[need] != 1e9) {
ans = min(ans, dep + cnt[need]);
}
}
else {
cnt[sum] = min(cnt[sum], dep);
v.push_back(sum);
}
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, -1, get_size(node, -1));
visited[centroid] = true;
cnt[0] = 0;
for (pair<int, int> u : adj[centroid]) {
if (!visited[u.first]) {
dfs(u.first, centroid, false, u.second, 1);
dfs(u.first, centroid, true, u.second, 1);
}
}
for (auto u : v) cnt[u] = INF;
v.clear();
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 = 0; i <= n - 1; i++) {
int u = H[i][0], v = H[i][1], w = L[i];
adj[u].push_back({ v, w });
adj[v].push_back({ u, w });
}
centroid_decomposition(1);
if (ans >= 1e9) return -1;
else 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... |