이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#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]);
}
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())
continue;
int tmp = distance(P.begin(), it);
array<int, 2> temp = P[tmp];
if(temp[0] == x+dx && temp[1] == y+dy){
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);
}
}
}
}
c.resize(N);
dfs(0, 0, N);
LCA D(N);
ans *= 2;
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 -= D.dist(it - P.begin(), i) - 1;
}
}
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... |