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 pb push_back
const int MAX_N = 200005;
vector <int> v[MAX_N];
int k, jog, par[MAX_N], cost[MAX_N];
map <int, int> m;
void dfs1 (int x, int pr) {
par[x] = pr;
for (int i : v[x]) {
if (i != pr) {
dfs1 (i, x);
}
}
}
void dfs2 (int x, int pr, int edges, int baha) {
if (baha > k) return;
m[baha] = edges;
for (int i : v[x]) {
if (i != pr and i != par[x]) {
dfs2 (i, pr, edges + 1, baha + cost[i]);
}
}
}
void dfs (int x, int pr, int baha, int edges) {
if (baha > k or pr == -1) {
return;
}
if ((baha + cost[x]) == k) {
if (jog == -1) jog = edges + 1;
else jog = min (jog, edges + 1);
return;
}
m.clear();
dfs2 (pr, x, 0, 0);
int jp = baha + cost[x];
if (m.find (k - jp) != m.end()) {
if (jog == -1) jog = edges + m[k - jp] + 1;
else jog = min (jog, edges + m[k - jp] + 1);
}
dfs (pr, par[pr], baha + cost[x], edges + 1);
}
int best_path(int N, int K, int H[][2], int L[]) {
jog = -1;
k = K;
for (int i = 0; i < N - 1 ; ++i) {
v[H[i][0]].pb (H[i][1]);
v[H[i][1]].pb (H[i][0]);
}
dfs1 (1, -1);
for (int i = 0; i < N - 1; ++i) {
if (par[H[i][0]] == H[i][1]) {
cost[H[i][0]] = L[i];
}
else if (par[H[i][1]] == H[i][0]) {
cost[H[i][1]] = L[i];
}
}
for (int i = 0; i < N; ++i) {
dfs (i, par[i], 0, 0);
}
return jog;
}
//int main () {
// freopen ("kk.txt", "r", stdin);
// int N, K;
// cin >> N >> K;
// int H[N][2], L[N];
// for (int i = 0; i < N; ++i) {
// cin >> H[i][0] >> H[i][1] >> L[i];
// }
//// best_path(N, K, H, L);
// cout << best_path(N, K, H, L);
//}
# | 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... |