# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1121422 | namprozz | 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>
#define ll long long
using namespace std;
const int MAXN = 200005;
int n;
ll k;
vector<pair<int, ll>> adj[MAXN];
int child[MAXN];
bool marked[MAXN];
void countChild(int u, int p)
{
child[u] = 1;
for(auto [v, w] : adj[u])
{
if(v == p or marked[v])
continue;
countChild(v, u);
child[u] += child[v];
}
}
int findCentroid(int u, int p, int n)
{
for(auto [v, w] : adj[u])
{
if(v == p or marked[v])
continue;
if(child[v] > n / 2)
{
return findCentroid(v, u, n);
}
}
return u;
}
int res = INT_MAX;
map<ll, int> dp;
void dfs(int u, int p, int d, ll tong)
{
if(tong > k)
return;
if(dp.count(k - tong))
{
res = min(res, d + dp[k - tong]);
}
for(auto [v, w] : adj[u])
{
if(v == p or marked[v])
continue;
dfs(v, u, d + 1, tong + w);
}
if(dp.count(tong))
{
dp[tong] = min(dp[tong], d);
}
else
{
dp[tong] = d;
}
}
void decomp(int u)
{
countChild(u, -1);
int c = findCentroid(u, -1, child[u]);
marked[c] = true;
dp.clear();
dp[0] = 0;
dfs(c, -1, 0, 0);
for(auto [v, w] : adj[c])
{
if(marked[v])
continue;
decomp(v);
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
for(int i = 0; i < n - 1; i++)
{
int u, v;
ll w;
cin >> u >> v >> w;
adj[u].push_back({v, w});
adj[v].push_back({u, w});
}
fill(marked, marked + n, false);
decomp(0);
if(res == INT_MAX)
{
cout << "-1" << '\n';
}
else
{
cout << res << '\n';
}
}