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>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;
#define getar(ar,n) for(ll i=0;i<n;++i) cin>>ar[i]
#define show(n) cout<<n<<'\n'
#define all(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 mxN = 1e6 + 50;
const ll MOD = 1e9 + 7;
const ll INF = 1e9;
const ld EPS = 1e-9;
vector<pair<ll,ll>> adj[mxN];
vector<ll> dp(mxN,INF);
ll sz[mxN],N,K,ans=INF;
bool ok[mxN];
void dfs(ll node,ll par){
sz[node]=0;
for(auto it:adj[node]){
if(it.first==par||ok[node]) continue;
dfs(it.first,node);
sz[node]+=sz[it.first];
}
sz[node]++;
}
int find(ll node,ll par){
for(auto it:adj[node]){
if(it.first==par||ok[node]) continue;
if(sz[it.first]>=((N+1)/2)){
return find(it.first,node);
}
}
return node;
}
void path_finder(ll u,ll par,ll h,ll 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(ll u,ll par,ll h,ll 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(ll u,ll par,ll 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);
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]});
}
N=n,K=k;
decompose(0);
return ans>=INF?-1:ans;
}
/*
int main(){
#ifndef ONLINE_JUDGE
freopen("input.in","r",stdin);
freopen("output.out","w",stdout);
#endif
int n,k;cin>>n>>k;
int h[n-1][2],l[n-1];
for(int i=0;i<n-1;++i){
cin>>h[i][0]>>h[i][1];
}
for(int i=0;i<n-1;++i){
cin>>l[i];
}
cout<<best_path(n,k,h,l);
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... |