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>
#include "race.h"
#define Task "test"
#define ll long long
#define pb emplace_back
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef pair<ll, ll> pii;
const int N = int(2e5) + 7;
map<ll, int>* s[N];
int n, k, u, v, w, res, p[N], sz[N], h[N];
ll d[N];
vector<pii> a[N];
//void Insert(int root, ll d, int _h)
//{
// pii found = *(s[root] -> lower_bound(mp(d, h[root])));
// if(found.fi == d) _h = min((ll)_h, found.se), s[root] -> erase(found);
// s[root] -> insert(mp(d, _h));
//}
void query(int u, int root)
{
ll dis = 2ll * d[root] + k - d[u];
//pii found = *(s[root] -> lower_bound(mp(dis, h[root])));
int& hi = (*s[root])[dis];
if(hi + h[u] - 2 * h[root] < res && hi) res = hi + h[u] - 2 * h[root];
for(pii adj: a[u])
if(adj.fi != p[u]) query(adj.fi, root);
}
void add(int u, int root)
{
int& hi = (*s[root])[d[u]];
if(!hi) hi = h[u];
else hi = min(hi, h[u]);
for(pii adj: a[u])
if(adj.fi != p[u]) add(adj.fi, root);
}
void DSU(int u)
{
int bigC = -1; sz[u] = 1;
for(pii adj: a[u]) {
if(adj.fi == p[u]) continue;
d[adj.fi] = d[u] + adj.se;
h[adj.fi] = h[u] + 1, p[adj.fi] = u;
DSU(adj.fi); sz[u] += sz[adj.fi];
if(bigC == -1 || sz[adj.fi] > sz[bigC]) bigC = adj.fi;
}
if(bigC != -1) s[u] = s[bigC];
else s[u] = new map<ll, int>();
int& hi = (*s[u])[d[u] + k];
if(hi) res = min(res, hi - h[u]);
int& irene = (*s[u])[d[u]];
if(!irene) irene = h[u];
else irene = min(irene, h[u]);
for(pii adj: a[u]) {
if(bigC == adj.fi || adj.fi == p[u]) continue;
query(adj.fi, u), add(adj.fi, u);
}
}
int best_path(int _n, int _k, int _h[][2], int _l[])
{
n = _n, k = _k;
for(int i = 0, lim = n - 1; i < lim; ++i) {
a[_h[i][0]].pb(_h[i][1], _l[i]), a[_h[i][1]].pb(_h[i][0], _l[i]);
}
res = n + 1; h[0] = p[0] = d[0] = 0;
DSU(0);
if(res == n + 1) return -1;
return res;
}
//int _h[N][2], _n, _k, _l[N];
//
//int main()
//{
// ios_base::sync_with_stdio(0);
// cin.tie(0), cout.tie(0);
// if(fopen(Task".inp", "r")) {
// freopen(Task".inp", "r", stdin);
// freopen(Task".out", "w", stdout);
// }
//
// cin >> _n >> _k;
// for(int i = 0; i < _n - 1; ++i) {
// cin >> _h[i][0] >> _h[i][1] >> _l[i];
// }
// cout << best_path(_n, _k, _h, _l);
//
// 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... |