This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
/* Bismillahir Rahmanir Rahim */
#include <bits/stdc++.h>
#include "factories.h"
using namespace std;
typedef pair <int, long long> pii;
const int N = 500005;
const long long oo = 1e18;
vector < vector <pii>> g(N);
int n;
int tot;
int sub[N];
int anc[N];
int vis[N];
int lst[N], t;
long long mn[N];
long long pre[N][25];
int idx[N];
void dfs0(int at, int par){
++tot;
sub[at] = 1;
for(auto u : g[at]){
if(vis[u.first] || u.first == par) continue;
dfs0(u.first, at);
sub[at] += sub[u.first];
}
}
int get(int at, int par){
for(auto u : g[at]){
if(vis[u.first] || u.first == par) continue;
if(sub[u.first] >= tot / 2) return get(u.first, at);
}
return at;
}
void get_dis(int at, int par, long long dis){
pre[at][++idx[at]] = dis;
for(auto u : g[at]){
if(vis[u.first] || u.first == par) continue;
get_dis(u.first, at, dis + u.second);
}
}
void decompose(int at, int par){
tot = 0;
dfs0(at, at);
int cen = get(at, at);
vis[cen] = 1;
if(par) anc[cen] = par;
get_dis(cen, cen, 0);
for(auto u : g[cen]){
if(vis[u.first]) continue;
decompose(u.first, cen);
}
}
void update(int from){
int cur = from;
for(int i = idx[from]; i >= 1; --i){
if(lst[cur] == t) mn[cur] = min(mn[cur], pre[from][i]);
else lst[cur] = t, mn[cur] = pre[from][i];
cur = anc[cur];
}
}
long long query(int from){
int cur = from;
long long ret = oo;
for(int i = idx[from]; i >= 1; --i){
if(lst[cur] == t) ret = min(ret, mn[cur] + pre[from][i]);
cur = anc[cur];
}
return ret;
}
long long Query(int S, int X[], int T, int Y[]){
++t;
for(int i = 0; i < S; ++i){
update(X[i] + 1);
}
long long ret = oo;
for(int i = 0; i < T; ++i){
ret = min(ret, query(Y[i] + 1));
}
return ret;
}
void Init(int N, int A[], int B[], int D[]){
n = N;
for(int i = 0; i < N - 1; ++i){
g[A[i] + 1].push_back({B[i] + 1, D[i]});
g[B[i] + 1].push_back({A[i] + 1, D[i]});
}
decompose(1, 0);
for(int i = 1; i <= n; ++i) mn[i] = oo;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |