This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include "factories.h"
#include <bits/stdc++.h>
#define Loop(x,l,r) for (ll x = (l); x < (r); ++x)
#define LoopR(x,l,r) for (ll x = (r)-1; x >= (l); --x)
typedef long long ll;
typedef std::pair<int, int> pii;
typedef std::pair<ll , ll > pll;
using namespace std;
const int N = 510'010;
const int lg = 19;
vector<pll> A[N];
vector<int> ord;
int rmq[lg+1][2*N];
int st[N], h[N];
ll dis[N];
int n;
void dfs(int v, int p, ll d, int h)
{
::h[v] = h;
st[v] = ord.size();
ord.push_back(v);
dis[v] = d;
for (auto [u, w] : A[v]) {
if (u != p) {
dfs(u, v, d + w, h+1);
ord.push_back(v);
}
}
}
#define HMIN(x, y) (h[x]<h[y]?(x):(y))
void rmq_init()
{
int n = ord.size();
Loop (i,0,n)
rmq[0][i] = ord[i];
Loop (i,0,lg)
for (int j = 0; j + (2<<i) <= n; ++j)
rmq[i+1][j] = HMIN(rmq[i][j], rmq[i][j+(1<<i)]);
}
ll get_dis(int x, int y)
{
ll ans = dis[x] + dis[y];
if (st[x] > st[y]) {
int tmp = x;
x = y;
y = tmp;
}
x = st[x];
y = st[y]+1;
int l = __lg(y - x);
int a = HMIN(rmq[l][x], rmq[l][y - (1<<l)]);
ans -= 2*dis[a];
return ans;
}
void Init(int N, int X[], int Y[], int D[])
{
n = N;
Loop (i,0,n) {
A[X[i]].push_back({Y[i],D[i]});
A[Y[i]].push_back({X[i],D[i]});
}
dfs(0, 0, 0, 0);
rmq_init();
}
ll dij(int s, int x[], int t, int y[])
{
static ll dis[N];
fill(dis, dis+N, (ll)1e18);
priority_queue<pair<ll,int>, vector<pair<ll,int>>, greater<pair<ll,int>>> q;
Loop (i,0,s) {
dis[x[i]] = 0;
q.push({0,x[i]});
}
while (q.size()) {
auto [d, v] = q.top();
q.pop();
if (d != dis[v])
continue;
for (auto [u, w] : A[v]) {
if (d + w < dis[u]) {
dis[u] = d + w;
q.push({dis[u], u});
}
}
}
ll ans = 1e18;
Loop (i,0,t)
ans = min(ans, dis[y[i]]);
return ans;
}
long long Query(int S, int X[], int T, int Y[])
{
if ((ll)S * T <= lg*n) {
ll ans = 1e18;
Loop (i,0,S) Loop (j,0,T)
ans = min(ans, get_dis(X[i], Y[j]));
return ans;
} else {
return dij(S, X, T, Y);
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |