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 <bits/stdc++.h>
using namespace std;
#define dbg(x) cout << "[" << #x << ": " << x << "] ";
const int64_t mod = 1e9;
vector<vector<int>> adj;
struct LCA{
vector<vector<int>> up;
int l;
vector<int> tin, tout;
vector<int64_t> depth;
LCA(int n){
l = 32 - __builtin_clz(n);
up.resize(l+1, vector<int>(n));
tin.resize(n);
tout.resize(n);
depth.resize(n);
dfs(0, 0);
}
int timer = 0;
void dfs(int node, int par){
tin[node] = timer++;
depth[node] = depth[par] + 1;
up[0][node] = par;
for(int i = 1; i <= l; i++)
up[i][node] = up[i-1][up[i-1][node]];
for(int v : adj[node]){
if(v == par)
continue;
dfs(v, node);
}
tout[node] = timer++;
}
bool isAncestor(int u, int v){
return tin[u] <= tin[v] && tout[u] >= tout[v];
}
int lca(int u, int v){
if(isAncestor(u, v))
return u;
if(isAncestor(v, u))
return v;
for(int i = l; i >= 0; --i)
if(!isAncestor(up[i][u], v))
u = up[i][u];
return up[0][u];
}
int64_t dist(int u, int v){
return depth[u] + depth[v] - 2*depth[lca(u, v)];
}
};
vector<int64_t> c;
vector<pair<int, int>> del = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
int64_t ans = 0;
void dfs(int node, int par, int N){
for(int v : adj[node]){
if(v == par)
continue;
dfs(v, node, N);
c[node] += c[v];
}
c[node]++;
ans += (c[node]*(N-c[node])) % mod;
ans %= mod;
}
int DistanceSum(int N, int *X, int *Y) {
adj.resize(N);
vector<array<int, 2>> P(N);
for(int i = 0; i < N; i++)
P[i] = {X[i], Y[i]};
sort(P.begin(), P.end());
vector<int> vis(N, 0);
queue<array<int, 3>> q;
q.push({P[0][0], P[0][1], 0});
vis[0] = 1;
while(!q.empty()){
array<int, 3> cur = q.front();
int x = cur[0], y = cur[1], idx = cur[2];
q.pop();
for(auto &[dx, dy] : del){
array<int, 2> t = {x+dx, y+dy};
auto it = lower_bound(P.begin(), P.end(), t);
if(it == P.end() || *it != t)
continue;
int tmp = it - P.begin();
if(!vis[tmp]){
vis[tmp] = 1;
adj[tmp].push_back(idx);
adj[idx].push_back(tmp);
// array<int, 3> p = {temp[0], temp[1], tmp};
// q.push(p);
q.push({t[0], t[1], tmp});
}
}
}
c.resize(N);
dfs(0, 0, N);
LCA D(N);
ans = (ans + ans) % mod;
for(int i = 0; i < N; i++){
auto [x, y] = P[i];
for(auto& [dx, dy] : del){
array<int, 2> t = {x+dx, y+dy};
auto it = lower_bound(P.begin(), P.end(), t);
if(it == P.end() || *it != t)
continue;
ans = (ans - D.dist(it - P.begin(), i) + 1 + mod) % mod;
}
}
ans /= 2;
ans %= mod;
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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |