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>
#define f first
#define s second
#define ll long long
#define pii pair<int,int>
using namespace std;
vector<pii> dir = {{0,1},{1,0},{-1,0},{0,-1}};
unordered_map<int,int> ar[100005], v[100005];
ll ans = 0, n;
ll cntX[100005], cntY[100005];
void dfs(int x, int y, ll sum) {
ans += sum;
v[x][y] = 1;
if (!v[x-1][y] && ar[x-1][y]) dfs(x-1,y,sum+cntX[n]-2*cntX[x-1]);
if (!v[x+1][y] && ar[x+1][y]) dfs(x+1,y,sum-cntX[n]+2*cntX[x]);
if (!v[x][y-1] && ar[x][y-1]) dfs(x,y-1,sum+cntY[n]-2*cntY[y-1]);
if (!v[x][y+1] && ar[x][y+1]) dfs(x,y+1,sum-cntY[n]+2*cntY[y]);
}
ll bfs(int sx, int sy) {
ll ans = 0;
queue<pair<pii,int>> nxt;
nxt.push({{sx,sy},0});
while (!nxt.empty()) {
auto tmp = nxt.front();
nxt.pop();
if (v[tmp.f.f][tmp.f.s]) continue;
v[tmp.f.f][tmp.f.s] = 1;
ans += tmp.s;
for (auto i : dir) {
if (!v[tmp.f.f+i.f][tmp.f.s+i.s] && ar[tmp.f.f+i.f][ tmp.f.s+i.s]) {
nxt.push({{tmp.f.f+i.f, tmp.f.s+i.s}, tmp.s+1});
}
}
}
return ans;
}
int DistanceSum(int N, int *X, int *Y) {
if (N <= 2000) {
int mnX = INT_MAX, mnY = INT_MAX;
for (int i = 0; i < N; i++) mnX = min(mnX, X[i]);
for (int i = 0; i < N; i++) mnY = min(mnY, Y[i]);
for (int i = 0; i < N; i++) X[i] -= mnX-1;
for (int i = 0; i < N; i++) Y[i] -= mnY-1;
ll ans = 0;
for (int i = 0; i < N; i++) ar[X[i]][Y[i]] = 1;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) v[X[j]][Y[j]] = 0;
ans += bfs(X[i],Y[i]);
}
return (ans/2) % 1'000'000'000;
} else {
n = N;
int mnX = INT_MAX, mnY = INT_MAX;
for (int i = 0; i < N; i++) mnX = min(mnX, X[i]);
for (int i = 0; i < N; i++) mnY = min(mnY, Y[i]);
for (int i = 0; i < N; i++) X[i] -= mnX-1;
for (int i = 0; i < N; i++) Y[i] -= mnY-1;
for (int i = 0; i < N; i++) cntX[X[i]]++, cntY[Y[i]]++;
for (int i = 1; i <= N; i++) cntX[i] += cntX[i-1], cntY[i] += cntY[i-1];
for (int i = 0; i < N; i++) ar[X[i]][Y[i]] = 1;
int tmp = 0;
for (int i = 1; i < N; i++) tmp += abs(X[i]-X[0]) + abs(Y[i]-Y[0]);
dfs(X[0], Y[0], tmp);
return (ans/2) % 1'000'000'000;
}
}
# | 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... |