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 <bits/stdc++.h>
using namespace std;
#define ll long long
// const ll MOD = 998244353;
const ll MOD = 1e9 + 7;
const ll NN = 2e5 + 2;
const ll KK = 1e6 + 2;
int n, k, ans = NN;
vector<int> is_dead(NN, 0), cnt(KK, -1), cnt1(KK, -1), sz(NN);
vector<vector<int>> edges(NN);
map<pair<int,int>, int> w;
set<int> s, s1;
void comp_sz (int node, int parent) {
sz[node] = 1;
for (int child : edges[node]) {
if (child == parent || is_dead[child]) continue;
comp_sz(child, node);
sz[node] += sz[child];
}
}
void dfs(int node, int parent, int dist, int lvl) {
s1.insert(dist), cnt1[dist] = (cnt1[dist] == -1 ? lvl : min(cnt1[dist], lvl));
for (int child : edges[node]) {
if (child == parent || is_dead[child]) continue;
dfs(child, node, dist + w[make_pair(child, node)], lvl + 1);
}
}
void find_cent (int node, int parent, int size) {
for (int child : edges[node]) {
if (child == parent || is_dead[child]) continue;
if (sz[child] * 2 > size) {
find_cent(child, node, size);
return;
}
}
// cout << node << "\n";
s.insert(0);
cnt[0] = 0;
for (int child : edges[node]) {
if (is_dead[child]) continue;
dfs(child, node, w[make_pair(child, node)], 1);
for (int x : s1) {
if (s.find(k - x) != s.end()) ans = min(ans, cnt1[x] + cnt[k - x]);
}
// cout << child << " | ";
for (int x : s1) {
s.insert(x);
// cout << x << " " << cnt1[x] << " | ";
cnt[x] = (cnt[x] == -1 ? cnt1[x] : min(cnt1[x], cnt[x]));
cnt1[x] = -1;
}
// cout << "\n";
s1.clear();
}
for (int x : s) {
// cout << x << " " << cnt[x] << " | ";
cnt[x] = -1;
}
// cout << "\n";
s.clear();
is_dead[node] = 1;
if (!is_dead[parent]){
comp_sz(parent, node);
find_cent(parent, node, sz[parent]);
}
for (int child : edges[node]) {
if (child == parent || is_dead[child]) continue;
comp_sz(child, node);
find_cent(child, node, sz[child]);
}
}
int best_path(int N, int K, int H[][2], int L[]){
n = N, k = K;
for (int i = 0; i < n - 1; i++) {
H[i][0]++, H[i][1]++;
edges[H[i][0]].push_back(H[i][1]);
edges[H[i][1]].push_back(H[i][0]);
}
for (int i = 0; i < n - 1; i++) {
w[make_pair(H[i][0], H[i][1])] = L[i];
w[make_pair(H[i][1], H[i][0])] = L[i];
}
is_dead[0] = 1;
comp_sz(1, 0);
find_cent(1, 0, n);
if (ans == NN) ans = -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... |