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 ll long long
#define pb push_back
#define task "tests"
#define pll pair<ll, ll>
#define pi pair<ll, pll>
#define fi first
#define se second
using namespace std;
const ll mod = 1e15+7;
const ll N = 5e5+5;
const int base = 313;
ll n, m, t, k, T, ans, tong, d[N], a[N][2], b[N], h[N], dp[N], cnt, top[N], nchain[N], chain, par[N];
vector<pll> adj[N];
ll pw(ll k, ll n)
{
ll total = 1;
for(; n; n >>= 1)
{
if(n & 1)total = total * k % mod;
k = k * k % mod;
}
return total;
}
void dfs(ll u, ll p)
{
d[u] = 1;
for(pll v: adj[u])
{
if(v.se == p)continue;
par[v.se] = u;
h[v.se] = h[u] + v.fi;
dfs(v.se, u);
d[u] += d[v.se];
}
}
void hld(ll u, ll p)
{
if(!top[chain])top[chain] = u;
nchain[u] = chain;
ll big = -1;
for(pll v : adj[u])
{
if(v.se == p)continue;
if(big == -1 || d[big] < d[v.se])big = v.se;
}
if(big != -1)hld(big, u);
for(pll v : adj[u])
{
if(v.se == p || v.se == big)continue;
++chain;
hld(v.se, u);
}
}
void Init(int N, int A[], int B[], int D[])
{
n = N;
for(int i = 0; i < n-1; i ++)
{
++A[i];
++B[i];
adj[A[i]].pb({D[i], B[i]});
adj[B[i]].pb({D[i], A[i]});
}
dfs(1, 0);
hld(1, 0);
}
struct node
{
ll chain, node, dep, id;
};
vector<node> kq, vi;
void getpath(ll u, ll dep, ll id)
{
while(u)
{
kq.pb({nchain[u], u, dep, id});
u = par[top[nchain[u]]];
}
}
bool cmp(const node& x, const node& y)
{
return x.chain < y.chain;
}
bool lf(const node& x, const node& y)
{
return h[x.node] < h[y.node];
}
void getans()
{
sort(vi.begin(), vi.end(), lf);
m = vi.size();
a[m][0] = a[m][1] = mod;
for(int i = m-1; i > 0; i --)
{
a[i][0] = a[i+1][0];
a[i][1] = a[i+1][1];
a[i][vi[i].id] = min(a[i][vi[i].id], vi[i].dep);
}
for(int i = 0; i < m; i ++)
{
tong = vi[i].dep + a[i+1][1-vi[i].id] - 2 * h[vi[i].node];
ans = min(ans, tong);
}
}
ll Query(int S, int X[], int T, int Y[])
{
ans = mod;
for(int i = 0; i < S; i ++)getpath(X[i]+1, h[X[i]+1], 0);
for(int i = 0; i < T; i ++)getpath(Y[i]+1, h[Y[i]+1], 1);
sort(kq.begin(), kq.end(), cmp);
int sz = kq.size();
for(int i = 0; i < sz; )
{
int j = i;
while(i < sz && kq[j].chain == kq[i].chain)
{
vi.pb(kq[i]);
//cout << kq[i].dep << " " << kq[i].node << '\n';
++i;
}
//cout << '\n';
getans();
vi.clear();
}
kq.clear();
return ans;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |