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 getar(ar,n) for(int i=0;i<n;++i) cin>>ar[i]
#define show(n) cout<<n<<'\n'
#define aint(v) v.begin(), v.end()
#define br cout<<"\n"
#define pb push_back
#define nl '\n'
#define yes cout<<"YES\n"
#define no cout<<"NO\n"
#define ret return
#define ll long long
#define ld long double
#define sza(x) ((int)x.size())
const int mxNN = 2e5+1000;
const int mxN = 1e6 + 500;
const int MOD = 1e9 + 7;
const int INF = 1e9;
const ld EPS = 1e-9;
vector<pair<int,int>> adj[mxNN];
vector<int> dp(mxN,INF);
vector<bool> ok(mxNN,0);
int sz[mxNN],K,ans=INF;
void dfs(int node,int par){
sz[node]=1;
for(auto it:adj[node]){
if(it.first==par||ok[node]) continue;
dfs(it.first,node);
sz[node]+=sz[it.first];
}
}
int find(int node,int par,int n){
for(auto it:adj[node]){
if(it.first==par||ok[node]) continue;
if(sz[it.first]*2>n){
return find(it.first,node,n);
}
}
return node;
}
void path_finder(int u,int par,int h,int tot){
if(tot>K) return;
ans=min(ans,dp[K-tot]+h);
for(auto it:adj[u]){
if(it.first!=par&&!ok[it.first]){
path_finder(it.first,u,h+1,tot+it.second);
}
}
}
void path_optimize(int u,int par,int h,int tot){
if(tot>K) return;
dp[tot]=min(dp[tot],h);
for(auto it:adj[u]){
if(it.first!=par&&!ok[it.first]){
path_optimize(it.first,u,h+1,tot+it.second);
}
}
}
void dp_reset(int u,int par,int tot){
if(tot>K) return;
dp[tot]=INF;
for(auto it:adj[u]){
if(it.first!=par&&!ok[it.first]){
dp_reset(it.first,u,tot+it.second);
}
}
}
void decompose(int u){
dfs(u,-1);
int cen=find(u,-1,sz[u]);
dp[0]=0;
for(auto it:adj[cen]){
if(!ok[it.first]){
path_finder(it.first,cen,1,it.second);
path_optimize(it.first,cen,1,it.second);
}
}
dp_reset(cen,-1,0);
ok[cen]=1;
for(auto it:adj[cen]){
if(!ok[it.first]){
decompose(it.first);
}
}
}
int best_path(int n,int k,int h[][2],int l[]){
for(int i=0;i<n-1;++i){
adj[h[i][0]].pb({h[i][1],l[i]});
adj[h[i][1]].pb({h[i][0],l[i]});
}
K=k;
decompose(0);
return ans>=INF?-1:ans;
}
# | 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... |