#include "factories.h"
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
template<class T>void minimize(T& a, T b){
if(a > b){
a = b;
}
}
const int lim = 5e5 + 5;
const ll INF = 1e18;
vector<pair<int, int>>e[lim];
int root = -1, cnt[lim], par[lim], h[lim], up[lim][19];
ll dis[lim], value[lim], par_d[lim][19];
bitset<lim>vis;
void dfs_1(int s){
for(auto& [d, w] : e[s]){
if(d != up[s][0]){
h[d] = h[up[d][0] = s] + 1;
dis[d] = dis[s] + w;
for(int i = 1; i < 19; i++){
up[d][i] = up[up[d][i - 1]][i - 1];
}
dfs_1(d);
}
}
}
void dfs_2(int s, int p = -1){
cnt[s] = 1;
for(auto& [d, w] : e[s]){
if(d != p){
dfs_2(d, s);
cnt[s] += cnt[d];
}
}
}
int get_centroid(int s, const int& n, int p = -1){
for(auto& [d, w] : e[s]){
if(d != p && !vis.test(d) && cnt[d] > (n >> 1)){
return get_centroid(d, n, s);
}
}
return s;
}
int centroid_decomposition(int s){
dfs_2(s);
int centroid = get_centroid(s, cnt[s]);
vis.set(centroid);
if(root == -1){
root = centroid;
par[centroid] = -1;
}
for(auto& [d, w] : e[centroid]){
if(!vis.test(d)){
par[centroid_decomposition(d)] = centroid;
}
}
return centroid;
}
int lca(int u, int v){
if(h[u] < h[v]){
swap(u, v);
}
int k = h[u] - h[v];
for(int i = 0; i < 19; i++){
if(1 << i & k){
u = up[u][i];
}
}
if(u == v){
return u;
}
for(int i = 18; i > -1; i--){
if(up[u][i] != up[v][i]){
u = up[u][i];
v = up[v][i];
}
}
return up[u][0];
}
ll get_distance(int u, int v){
return dis[u] + dis[v] - (dis[lca(u, v)] << 1LL);
}
void Init(int n, int a[], int b[], int d[]){
for(int i = 0; i + 1 < n; i++){
e[a[i]].emplace_back(b[i], d[i]);
e[b[i]].emplace_back(a[i], d[i]);
}
memset(up, dis[1] = 0, sizeof(up));
dfs_1(0);
vis.reset();
centroid_decomposition(0);
for(int i = 0; i < n; value[i++] = INF){
int u = i;
for(int cnt = 0; u != -1; cnt++, u = par[u]){
par_d[i][cnt] = get_distance(u, i);
}
}
}
ll Query(int S, int X[], int T, int Y[]){
ll ans = INF;
for(int i = 0; i < S; i++){
int u = X[i];
for(int cnt = 0; u != -1; cnt++, u = par[u]){
minimize(value[u], par_d[X[i]][cnt]);
}
}
for(int i = 0; i < T; i++){
int u = Y[i];
for(int cnt = 0; u != -1; cnt++, u = par[u]){
minimize(ans, value[u] + par_d[Y[i]][cnt]);
}
}
for(int i = 0; i < S; i++){
int u = X[i];
for(int cnt = 0; u != -1; cnt++, u = par[u]){
value[u] = INF;
}
}
return ans;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
18 ms |
80476 KB |
Output is correct |
2 |
Incorrect |
618 ms |
84904 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
13 ms |
78424 KB |
Output is correct |
2 |
Execution timed out |
8039 ms |
98216 KB |
Time limit exceeded |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
18 ms |
80476 KB |
Output is correct |
2 |
Incorrect |
618 ms |
84904 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |