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;
using pii = pair<int, int>;
const int SIZE = 200000;
vector<pii> G[SIZE];
bitset<SIZE> vis;
int sub[SIZE];
int ans = INT_MAX;
int calc(int V, int P) {
sub[V] = 1;
for(pii X : G[V])
if (!vis[X.first] and X.first != P)
sub[V] += calc(X.first, V);
return sub[V];
}
int centroid(int V, int P, int sz) {
for(pii X : G[V])
if (!vis[X.first] and X.first != P and sub[X.first] > sz / 2)
return centroid(X.first, V, sz);
return V;
}
void calc2(int V, int P, int len, int cost, int K, map<int, int> &m) {
if (cost > K)
return;
if (m.find(cost) == m.end())
m[cost] = len;
else
m[cost] = min(m[cost], len);
for(pii X : G[V])
if (!vis[X.first] and X.first != P)
calc2(X.first, V, len + 1, cost + X.second, K, m);
}
void centroidDecomposite(int V, int K) {
calc(V, -1);
int C = centroid(V, -1, sub[V]);
map<int, int> sum;
sum[0] = 0;
for(pii X : G[C]) {
map<int, int> tmp;
calc2(X.first, C, 1, X.second, K, tmp);
for(pii Y : tmp) {
int cost = Y.first, len = Y.second;
if (sum.find(K - cost) == sum.end()) continue;
ans = min(ans, len + sum[K - cost]);
}
}
vis[C] = true;
for(pii X : G[C])
if (!vis[X.first])
centroidDecomposite(X.first, K);
}
int best_path(int N, int K, int H[][2], int L[]) {
for(int i = 0; i < N - 1; i++) {
G[H[i][0]].emplace_back(make_pair(H[i][1], L[i]));
G[H[i][1]].emplace_back(make_pair(H[i][0], L[i]));
}
centroidDecomposite(0, K);
return ans == INT_MAX ? -1 : ans;
}
/*
int A[SIZE - 1][2];
int B[SIZE - 1];
int main() {
int n, k;
cin >> n >> k;
for(int i = 0; i < n - 1; i++)
cin >> A[i][0] >> A[i][1];
for(int i = 0; i < n - 1; i++)
cin >> B[i];
cout << best_path(n, k, A, B) << '\n';
return 0;
}
*/
# | 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... |