#include "factories.h"
#include<bits/stdc++.h>
#define ll long long
#define MAXN 500002
using namespace std;
vector<vector<pair<int,ll>>>Tr(MAXN);
bool used[MAXN]={};
int subtree[MAXN];
vector<vector<pair<int,ll>>>centroids(MAXN);
void subtreedfs(int node, int p=-1)
{
subtree[node]=1;
for(auto i:Tr[node]) if(!used[i.first] && i.first!=p)
{
subtreedfs(i.first,node);
subtree[node]+=subtree[i.first];
}
}
int getCentroid(int node, int subsz, int p=-1)
{
for(auto i:Tr[node]) if(i.first!=p && !used[i.first] && subtree[i.first]*2>subsz) return getCentroid(i.first,subsz,node);
return node;
}
void dfscen(int node, int cn, int p=-1, ll dist=0)
{
centroids[node].push_back({cn, dist});
for(auto i:Tr[node]) if(i.first!=p && !used[i.first]) dfscen(i.first,cn,node, dist+i.second);
}
void cenDec(int node)
{
subtreedfs(node);
int c=getCentroid(node,subtree[node]);
dfscen(c,c);
used[c]=true;
for(auto i:Tr[c]) if(!used[i.first]) cenDec(i.first);
}
map<int,ll>df;
void Init(int N, int A[], int B[], int D[]) {
for(int i=0;i<N-1;i++)
{
Tr[A[i]].emplace_back(B[i],D[i]);
Tr[B[i]].emplace_back(A[i],D[i]);
}
cenDec(0);
}
long long Query(int S, int X[], int T, int Y[]) {
for(int i=0;i<S;i++)
{
for(auto j:centroids[X[i]]) df[j.first]=LLONG_MAX/4;
}
for(int i=0;i<T;i++)
{
for(auto j:centroids[Y[i]]) df[j.first]=LLONG_MAX/4;
}
for(int i=0;i<T;i++)
{
for(auto j:centroids[Y[i]]) df[j.first]=min(df[j.first],j.second);
}
ll ans=LLONG_MAX/4;
for(int i=0;i<S;i++)
{
for(auto j:centroids[X[i]]) ans=min(ans,df[j.first]+j.second);
}
return 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... |