# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
633474 | LeonaRaging | Race (IOI11_race) | C++14 | 0 ms | 0 KiB |
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 fi first
#define se second
#define ll long long
#define pb push_back
#define db(val) "[" #val " = " << (val) << "] "
const ll mod = 1e9 + 7;
const int maxn = 2e5 + 4;
const int INF = 1e9;
int n, k, res;
set<pair<int,int>> adj[maxn];
map<ll,int> L, cur;
void dfs(int u, int p, ll dis, int len) {
if (dis > k) return;
cur[dis] = len;
auto it = L.find(k - dis);
if (it != L.end())
res = min(res, len + it->se);
for (auto it : adj[u]) {
int v; ll w; tie(v, w) = it;
if (v == p) continue;
dfs(v, u, dis + w, len + 1);
}
}
void Solve(int u) {
L.clear();
L[0] = 0;
for (auto it : adj[u]) {
int v; ll w; tie(v, w) = it;
cur.clear();
dfs(v, u, w, 1);
for (auto it : cur) {
if (L.find(it.fi) == L.end()) L[it.fi] = it.se;
else L[it.fi] = min(L[it.fi], it.se);
}
}
}
struct CentroidDecomposition {
int sz[maxn];
int dfs(int u, int p) {
sz[u] = 1;
for (auto it : adj[u])
if (it.fi != p) sz[u] += dfs(it.fi, u);
return sz[u];
}
int Centroid(int u, int p, int tot) {
for (auto it : adj[u])
if (it.fi != p && sz[it.fi] > tot / 2)
return Centroid(it.fi, u, tot);
return u;
}
void build(int u) {
int tot = dfs(u, 0);
int c = Centroid(u, 0, tot);
Solve(c);
vector<pair<int,int>> del(adj[c].begin(), adj[c].end());
for (auto it : del) {
int v, w; tie(v, w) = it;
adj[c].erase(it);
adj[v].erase(adj[v].find({c, w}));
build(v);
}
}
} Cen;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
//freopen(".INP", "r", stdin);
//freopen(".OUT", "w", stdout);
cin >> n >> k;
for (int i = 1; i < n; i++) {
int u, v, w; cin >> u >> v >> w;
u++, v++;
adj[u].insert({v, w});
adj[v].insert({u, w});
}
res = INF;
Cen.build(1);
cout << (res == INF ? -1 : res);
}