# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
975950 | Amaarsaa | 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 el '\n'
#define fi first
#define sc second
//#define int ll
#define pii pair<int, int>
#define all(v) v.begin(), v.end()
using namespace std;
using ll=long long;
using ull=unsigned long long;
using ld=long double;
const int mod=1e9+7;
const int N=2e5+11;
const int lim=1e6+11;
int n, k, sz[N], vit[N], dp[lim], mx;
vector<int> ned;
int ans=-1;
vector<pii> adj[N];
int subtree(int u, int pa)
{
sz[u] = 1;
for (auto v: adj[u])
{
if (v.fi != pa && !vit[v.fi])
{
sz[u] += subtree(v.fi, u);
}
}
return sz[u];
}
int cen(int u, int pa, int n)
{
for (auto v: adj[u])
{
if (v.fi != pa && !vit[v.fi] && sz[v.fi] > n/2)
{
return cen(v.fi, u, n);
}
}
return u;
}
void dfs(int u, int pa, int dis, int h, int ch)
{
if(dis > k) return;
if(ch)
{
if(dp[dis]==-1) dp[dis]=h;
else dp[dis]=min(dp[dis], h);
ned.push_back(dis);
}
else
{
if(dp[k-dis]!=-1)
{
if(ans==-1) ans=dp[k-dis]+h;
else ans=min(ans, dp[k-dis]+h);
}
}
for(auto v: adj[u])
{
if(v.fi != pa && !vit[v.fi]) dfs(v.fi, u, dis+v.sc, h+1, ch);
}
}
void calc(int u)
{
subtree(u, 0);
int c = cen(u, 0, sz[u]);
vit[c] = 1;
for(auto u: adj[c])
{
if (!vit[u.fi])
{
dfs(u.fi, c, u.sc, 1, 0);
dfs(u.fi, c, u.sc, 1, 1);
}
}
for(int x : ned) dp[x]=-1;
ned.clear();
for(auto v: adj[c])
{
if (!vit[v.fi])
{
calc(v.fi);
}
}
}
void sol()
{
cin >> n >> k;
for(int i=1, u, v, x; i<n; i++)
{
cin >> u >> v >> x;
adj[u+1].push_back({v+1, x});
adj[v+1].push_back({u+1, x});
}
memset(dp, -1, sizeof dp);
dp[0]=0;
calc(1);
cout << ans;
}
signed main()
{
// freopen("divisor.INP", "r", stdin);
// freopen("divisor.OUT", "w", stdout);
ios_base::sync_with_stdio(0);
cin.tie(0);
int t=1;
//cin >> t;
while(t--)
{
sol();
}
}