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;
using i64 = int64_t;
const array<int, 2> mv[4] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
const int Z = 1e5;
int n, s[Z];
map<int, int> toS[Z];
set<int> g[Z], h[Z];
void dfs(int u, int p) {
for(const int &v : g[u]) if(v != p) {
dfs(v, u);
s[u] += toS[u][v] = s[v];
toS[v][u] = n - s[v];
}
}
i64 curSum, ans;
void cnt(int u) {
s[u] = 1;
ans += curSum;
for(const int &v : h[u]) if(!s[v]) {
curSum += i64(n - 2 * toS[u][v]);
cnt(v);
curSum -= i64(n - 2 * toS[u][v]);
}
}
int DistanceSum(int N, int *X, int *Y) {
map<int, map<int, int>> cAt;
int o[N], id[N]; n = N;
for(int i = 0; i < N; ++i)
cAt[X[i]][Y[i]] = (o[i] = i) + 1;
for(int u = 0; u < N; ++u) {
for(const auto &[dx, dy] : mv) {
int v = cAt[X[u] + dx][Y[u] + dy] - 1;
if(v >= 0) h[u].insert(v);
}
}
for(int _ = 0; _ < 2; ++_) {
if(_) {
cAt.clear();
for(int i = 0; i < N; ++i)
cAt[X[i]][Y[i]] = i + 1;
}
sort(o, o + N, [&](const int &i, const int &j) {
return Y[i] < Y[j];
});
for(const int &u : o) {
int v = cAt[X[u]][Y[u] - 1] - 1;
id[u] = v < 0 ? u : id[v];
}
fill(s, s + N, 0);
fill(g, g + N, set<int> ());
for(int u = 0; u < N; ++u) {
++s[id[u]];
for(const int &v : h[u]) if(id[u] != id[v])
g[id[u]].insert(id[v]);
}
dfs(id[0], id[0]);
for(int u = 0; u < N; ++u)
for(const int &v : h[u]) if(id[u] != id[v])
toS[u][v] = toS[id[u]][id[v]];
swap(X, Y);
}
queue<pair<int, int>> q;
bool vis[N] {1};
q.emplace(0, 0);
while(!empty(q)) {
auto [u, d] = q.front(); q.pop();
curSum += i64(d);
for(const int &v : h[u])
if(v >= 0 && !vis[v])
vis[v] = 1, q.emplace(v, d + 1);
}
fill(s, s + N, 0);
cnt(0);
return (ans >> 1) % i64(1e9);
}
# | 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... |