#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][18];
ll dis[lim], value[lim], D[lim][19];
bitset<lim>vis;
void dfs_1(int s){
for(auto& [d, w] : e[s]){
if(d != up[s][0]){
h[up[s][0] = d] = h[s] + 1;
dis[d] = dis[s] + w;
for(int i = 1; i < 18; 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(1);
vis.reset();
centroid_decomposition(1);
for(int i = 1; i <= n; value[i++] = INF){
int u = i;
for(int cnt = 0; u != -1; cnt++, u = par[u]){
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], 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] + 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 |
Runtime error |
1018 ms |
524288 KB |
Execution killed with signal 9 |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
875 ms |
524288 KB |
Execution killed with signal 9 |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
1018 ms |
524288 KB |
Execution killed with signal 9 |
2 |
Halted |
0 ms |
0 KB |
- |