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;
ll n, k, ans = NN;
vector<ll> is_dead(NN, 0), cnt(KK, -1), cnt1(KK, -1), sz(NN);
vector<vector<ll>> edges(NN);
map<pair<ll,ll>, ll> w;
set<ll> s, s1;
void comp_sz (ll node, ll parent) {
sz[node] = 1;
for (ll child : edges[node]) {
if (child == parent || is_dead[child]) continue;
comp_sz(child, node);
sz[node] += sz[child];
}
}
void dfs(ll node, ll parent, ll dist, ll lvl) {
s1.insert(dist), cnt1[dist] = (cnt1[dist] == -1 ? lvl : min(cnt1[dist], lvl));
for (ll child : edges[node]) {
if (child == parent || is_dead[child]) continue;
dfs(child, node, dist + w[make_pair(child, node)], lvl + 1);
}
}
void find_cent (ll node, ll parent, ll size) {
for (ll child : edges[node]) {
if (child == parent || is_dead[child]) continue;
if (sz[child] * 2 > size) {
find_cent(child, node, size);
return;
}
}
s.insert(0);
cnt[0] = 0;
for (ll child : edges[node]) {
if (is_dead[child]) continue;
dfs(child, node, w[make_pair(child, node)], 1);
for (ll x : s1) {
if (s.find(k - x) != s.end()) ans = min(ans, cnt1[x] + cnt[k - x]);
}
for (ll x : s1) {
s.insert(x);
cnt[x] = (cnt[x] == -1 ? cnt1[x] : min(cnt1[x], cnt[x]));
cnt1[x] = -1;
}
s1.clear();
}
for (ll x : s) {
cnt[x] = -1;
}
s.clear();
is_dead[node] = 1;
for (ll child : edges[node]) {
if (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... |