#include<bits/stdc++.h>
#define fori(i,a,b) for(int i=a;i<=b;i++)
#define pb push_back
using namespace std;
typedef pair<long long,long long> ii;
typedef tuple<int,int,int> tp;
const int M = 1e6 + 10;
const int N = 1e3 + 10;
const int mod = 1e9 + 7;
int n, q;
vector<ii> ke[M];
int num[M], tail[M], cnt = 0, up[M][20];
long long d[M];
void dfs(int u,int p = 0)
{
num[u] = ++ cnt;
for(int i = 1;i <= 19; i++) up[u][i] = up[up[u][i - 1]][i - 1];
for(ii tmp : ke[u]) {
int v = tmp.first, w = tmp.second;
if(v == p) continue;
d[v] = d[u] + w;
up[v][0] = u;
dfs(v,u);
}
tail[u] = cnt;
}
bool anc(int u,int v)
{
return num[u] <= num[v] && tail[u] >= tail[v];
}
int lca(int u,int v)
{
if(anc(u,v)) return u;
if(anc(v,u)) return v;
for(int i = 19; i >= 0; i--) if(!anc(up[u][i],v)) u = up[u][i];
return up[u][0];
}
long long dist(int u,int v)
{
int x = lca(u,v);
return d[u] + d[v] - 2 * d[x];
}
vector<ii> adj[M];
long long D[M];
bool cmp(const int &a,const int &b) {
return num[a] < num[b];
}
void Init(int N, int A[], int B[], int D[]) {
n = N;
for(int i = 0;i < n - 1; i++) {
int u = A[i], v = B[i], w = D[i];
u ++, v ++;
ke[u].pb({v,w});
ke[v].pb({u,w});
}
up[1][0] = 1;
dfs(1,0);
for(int i = 1;i <= n; i++) D[i] = 1e9;
}
long long Query(int S, int X[], int T, int Y[]){
vector<int> Q;
for(int i = 0;i < S; i++) {
int u = X[i];
u++;
Q.pb(u);
}
for(int i = 0;i < T; i++) {
int u = Y[i];
u++;
Q.pb(u);
}
sort(Q.begin(), Q.end(),cmp);
Q.resize(unique(Q.begin(), Q.end()) - Q.begin());
int m = Q.size();
for(int i = 1;i <= m - 1; i++) {
Q.pb(lca(Q[i - 1],Q[i]));
//cout << Q[i - 1] << " " << Q[i] << " " << lca(Q[i], Q[i - 1]) << "\n";
}
sort(Q.begin(), Q.end(), cmp);
Q.resize(unique(Q.begin(), Q.end()) - Q.begin());
stack<int> sk;
for(int v : Q) {
while(!sk.empty() && !anc(sk.top(),v)) sk.pop();
if(!sk.empty()) {
int w = dist(v,sk.top());
adj[v].pb({sk.top(),w});
adj[sk.top()].pb({v,w});
}
sk.push(v);
}
while(!sk.empty()) {
int v = sk.top();sk.pop();
if(!sk.empty()) {
int w = dist(v,sk.top());
adj[v].pb({sk.top(),w});
adj[sk.top()].pb({v,w});
}
}
priority_queue<ii, vector<ii>, greater<ii> > h;
for(int i = 0;i < S; i++) {
int v = X[i];
D[v] = 0;
h.push({0,v});
}
while(!h.empty()) {
int u, val;
tie(val,u) = h.top();h.pop();
if(D[u] < val) continue;
for(ii tmp : adj[u]) {
int v = tmp.first, w = tmp.second;
if(D[v] > D[u] + w) {
D[v] = D[u] + w;
h.push({D[v],v});
}
}
}
long long kq = 1e15;
for(int i = 0;i < T; i++) kq = min(kq, D[Y[i]]);
for(int v : Q) {
adj[v].clear();
D[v] = 1e15;
}
return kq;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |