#include "factories.h"
#include "bits/stdc++.h"
using namespace std;
#define int long long
const int NM = 5e5 + 5;
const int LG = __lg(NM);
int n;
vector<pair<int, int>> adj[NM];
bool visited[NM];
vector<int> tour;
int depth[NM], tin[NM], tout[NM];
long long dist[NM];
pair<int, int> ST[LG + 2][NM << 1];
void dfs_euler_tour(const int &u) {
visited[u] = 1;
tin[u] = tour.size();
tour.emplace_back(u);
for (auto &[v, w]: adj[u])
if (!visited[v]) {
depth[v] = depth[u] + 1;
dist[v] = dist[u] + w;
dfs_euler_tour(v);
tour.emplace_back(u);
}
tout[u] = tour.size() - 1;
}
void build_sparse_table() {
for (int i = 0; i < (int)tour.size(); ++i)
ST[0][i] = {depth[tour[i]], tour[i]};
for (int i = 1; i <= LG + 1; ++i)
for (int j = 0; j + (1 << i) - 1 < (int)tour.size(); ++j)
ST[i][j] = min(ST[i - 1][j], ST[i - 1][j + (1 << (i - 1))]);
}
int lca(const int &u, const int &v) {
int l = tin[u], r = tin[v];
if (l > r) swap(l, r);
int k = __lg(r - l + 1);
return min(ST[k][l], ST[k][r - (1 << k) + 1]).second;
}
void Init(int N, int A[], int B[], int D[]) {
n = N;
for (int i = 0; i < n - 1; ++i) {
adj[A[i]].emplace_back(B[i], D[i]);
adj[B[i]].emplace_back(A[i], D[i]);
}
dfs_euler_tour(0);
build_sparse_table();
}
bool cmp(const int &u, const int &v) {
return tin[u] < tin[v];
}
bool is_anc(const int &u, const int &v) {
return tin[u] <= tin[v] && tin[v] <= tout[u];
}
vector<pair<int, long long>> new_adj[NM];
priority_queue<pair<long long, int>> q;
long long d[NM];
long long Query(int S, int X[], int T, int Y[]) {
vector<int> node;
for (int i = 0; i < S; ++i)
node.emplace_back(X[i]);
for (int i = 0; i < T; ++i)
node.emplace_back(Y[i]);
sort(node.begin(), node.end(), cmp);
node.erase(unique(node.begin(), node.end()), node.end());
int tmp = node.size();
for (int i = 0; i + 1 < tmp; ++i)
node.emplace_back(lca(node[i], node[i + 1]));
sort(node.begin(), node.end(), cmp);
node.erase(unique(node.begin(), node.end()), node.end());
for (auto &i: node) {
new_adj[i].clear();
visited[i] = 0;
d[i] = 1e18;
}
for (int i = 0; i < S; ++i) {
d[X[i]] = 0;
q.push({0, X[i]});
}
stack<int> st;
st.push(node[0]);
for (int i = 1; i < (int)node.size(); ++i) {
while (!is_anc(st.top(), node[i]))
st.pop();
new_adj[st.top()].emplace_back(node[i], dist[node[i]] - dist[st.top()]);
new_adj[node[i]].emplace_back(st.top(), dist[node[i]] - dist[st.top()]);
st.push(node[i]);
}
while (!q.empty()) {
int u = q.top().second;
q.pop();
if (visited[u]) continue;
visited[u] = 1;
for (auto &[v, w]: new_adj[u])
if (d[v] > d[u] + w) {
d[v] = d[u] + w;
q.push({d[v], v});
}
}
long long ans = 1e18;
for (int i = 0; i < T; ++i)
ans = min(ans, d[Y[i]]);
return ans;
}
Compilation message
/usr/bin/ld: /tmp/ccaoyDBW.o: in function `main':
grader.cpp:(.text.startup+0x37d): undefined reference to `Init(int, int*, int*, int*)'
/usr/bin/ld: grader.cpp:(.text.startup+0x412): undefined reference to `Query(int, int*, int, int*)'
collect2: error: ld returned 1 exit status