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 "race.h"
#include<bits/stdc++.h>
using namespace std;
#define in pair<int, int>
#define f first
#define s second
#define pb push_back
#define pob pop_back
#define INF (int)1e9
#define MX (int)2e5+5
#define LMX (int)1e6+5
#define fast() ios_base::sync_with_stdio(false); cin.tie(NULL)
int n, k;
vector<in> adj[MX];
int sz[MX];
bool cut[MX];
void calc_subtree(int u, int p)
{
sz[u] = 1;
for(auto [v, w]: adj[u])
{
if(v==p)
continue;
if(cut[v])
continue;
calc_subtree(v, u);
sz[u]+=sz[v];
}
return;
}
int centroid(int root, int u, int p)
{
for(auto [v, w]: adj[u])
{
if(cut[v])
continue;
if(v==p)
continue;
if(2*sz[v] > sz[root])
return centroid(root, v, u);
}
return u;
}
vector<int> curr;
vector<int> on;
vector<int> best(LMX, INF);
int ans = INF;
void ritul(int u, int p, int lvl, int dist)
{
if(dist > k)
return;
ans = min(ans, lvl+best[k-dist]);
for(auto [v, w]: adj[u])
{
if(v==p)
continue;
if(cut[v])
continue;
if((dist+w) > k)
continue;
ritul(v, u, lvl+1, dist+w);
}
return;
}
void ritul2(int u, int p, int lvl, int dist)
{
if(dist > k)
return;
curr.pb(dist);
best[dist] = min(best[dist], lvl);
for(auto [v, w]: adj[u])
{
if(v==p)
continue;
if(cut[v])
continue;
if((dist+w) > k)
continue;
ritul2(v, u, lvl+1, dist+w);
}
return;
}
void centroid_decomp(int u)
{
calc_subtree(u, -1);
int root = centroid(u, u, -1);
cut[root] = 1;
curr.clear();
for(auto [v, w]: adj[root])
{
if(cut[v])
continue;
ritul(v, root, 1, w);
ritul2(v, root, 1, w);
}
for(int t: curr)
best[t] = INF;
for(auto [v, w]: adj[root])
{
if(cut[v])
continue;
centroid_decomp(v);
}
return;
}
int best_path(int N, int K, int h[][2], int L[])
{
n = N;
k = K;
for(int i = 0; i < n-1; i++)
{
int u = h[i][0];
int v = h[i][1];
u++;
v++;
int l = L[i];
adj[u].pb({v, l});
adj[v].pb({u, l});
}
centroid_decomp(1);
if(ans == INF)
ans = -1;
return ans;
}
/*
signed main()
{
int V, KK;
cin >> V >> KK;
int h[V-1][2];
int L[V-1];
for(int i = 0; i < V-1; i++)
cin >> h[i][0] >> h[i][1] >> L[i];
int ok = best_path(V, KK, h, L);
cout << ok << endl;
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... |