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;
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
const int mxNN = 2e5+1000;
const int mxN = 1e6 + 500;
const int INF = (int) 1e9;
vector<pair<int,int>> adj[mxNN];
int sz[mxNN],dp[mxN],K,ans=INF;
bool ok[mxNN];
void dfs(int node,int par){
sz[node]=1;
for(auto it:adj[node]){
int adj=it.first;
if(par!=adj&&!ok[adj]){
dfs(adj,node);
sz[node]+=sz[adj];
}
}
}
int find(int node,int par,int n){
for(auto it:adj[node]){
int adj=it.first;
if(par!=adj&&!ok[adj]&&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]){
if(tot+it.second>K) continue;
path_finder(it.first,u,h+1,tot+it.second);
}
}
}
void path_optimize(int u,int par,int h,int tot,unordered_set<int> &st){
if(tot>K) return;
st.insert(tot);
dp[tot]=min(dp[tot],h);
for(auto it:adj[u]){
if(it.first!=par&&!ok[it.first]){
if(tot+it.second>K) continue;
path_optimize(it.first,u,h+1,tot+it.second,st);
}
}
}
void decompose(int u){
dfs(u,0);
int cen=find(u,0,sz[u]);
dp[0]=0;
unordered_set<int> st;
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,st);
}
}
for(auto it:st) dp[it]=INF;
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]].emplace_back(h[i][1],l[i]);
adj[h[i][1]].emplace_back(h[i][0],l[i]);
}
memset(dp,0x3f,sizeof(dp));
K=k;
decompose(0);
return ans>=INF?-1:ans;
}
Compilation message (stderr)
race.cpp:6: warning: ignoring '#pragma GCC optimization' [-Wunknown-pragmas]
6 | #pragma GCC optimization ("O3")
|
race.cpp:7: warning: ignoring '#pragma GCC optimization' [-Wunknown-pragmas]
7 | #pragma GCC optimization ("unroll-loops")
|
# | 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... |