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 ll long long int
#define vi vector<int>
#define vll vector<ll>
#define vvi vector < vi >
#define pii pair<int,int>
#define pll pair<long long, long long>
#define mod 1000000007
#define inf 9999999999;
#define all(c) c.begin(),c.end()
#define mp(x,y) make_pair(x,y)
#define pb push_back
#define in insert
#define f first
#define s second
#define pi 3.141592653589793238
using namespace std;
const int MAXN = 1e6+5;
const int INF = 1e7;
int n,k;
set<int>adj[MAXN];
map<pair<int,int>,int> wt;
int sz[MAXN];
int currsize;
int ans = INF;
int cnt[MAXN];
int glob[MAXN];
void dfs(int u,int p){
sz[u] = 1;
currsize++;
for(auto v:adj[u]){
if(v != p){
dfs(v,u);
sz[u] += sz[v];
}
}
}
int dfs2(int u,int p){
for(auto v:adj[u]){
if(v != p && sz[v] > currsize/2){
return dfs2(v,u);
}
}
return u;
}
void dfs3(int u,int p,int sum,int dep){
if(sum <= k){
cnt[sum] = min(cnt[sum],dep);
ans = min(ans,glob[k-sum] + cnt[sum]);
}
for(auto v:adj[u]){
if(v != p){
dfs3(v,u,sum + wt[{u,v}],dep+1);
}
}
}
void decompose(int u,int p){
currsize=0;
dfs(u,p);
int c = dfs2(u,p);
// cout << c <<endl;
for(auto v:adj[c]){
for(int i =1;i<=k;i++) cnt[i] =INF;
dfs3(v,c,wt[{c,v}],1);
for(int i =1;i<=k;i++) glob[i] = min(glob[i],cnt[i]);
}
// look in the subtree of c
for(auto v:adj[c]){
adj[v].erase(c);
decompose(v,c);
}
adj[c].clear();
}
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 w = L[i];
wt[{u,v}] = w;
wt[{v,u}] = w;
adj[u].in(v);
adj[v].in(u);
}
for(int i =1;i<=k;i++) glob[i] = INF;
decompose(1,-1);
// for(int i = 1;i<=k;i++) cout << glob[i] << endl;
if(ans == INF) ans = -1;
return ans;
// cout << ans << endl;
}
// int main()
// {
// std::ios::sync_with_stdio(false);
// int h[3][2];
// h[0][0] = 0;
// h[0][1] = 1;
// h[1][0] = 1;
// h[1][1] = 2;
// h[2][0] = 2;
// h[2][1] = 3;
// int l[3];
// l[0] = 1;
// l[1] = 2;
// l[2] = 4;
// cout << best_path(4,3,h,l) << endl;
// // cin >> n;
// // cin >> k;
// // for(int i =2;i<=n;i++){
// // int u,v;
// // cin >> u >> v;
// // int w;
// // cin >> w;
// // wt[{u,v}] = w;
// // wt[{v,u}] = w;
// // adj[u].in(v);
// // adj[v].in(u);
// // }
// // for(int i =1;i<=k;i++) glob[i] = INF;
// // decompose(1,-1);
// // // for(int i = 1;i<=k;i++) cout << glob[i] << endl;
// // if(ans == INF) ans = -1;
// // cout << ans << 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... |