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 <iostream>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
#define oo 1000000000
#define ll long long
#define pb push_back
#define pii pair<int, int>
const ll m = 1e9;
vector<int> val;
vector<vector<int>> ed;
map<pii, int> mp;
vector<ll> sm;
void init(int n){
val.clear();
val.resize(n+1);
ed.clear();
ed.resize(n+1);
sm.clear();
sm.resize(n+1);
mp.clear();
}
void build_tree(int n, int k, int *x, int *y){
init(n);
vector<vector<int>> v(k+1);
for (int i = 0; i < n; ++i) {
v[x[i]].pb(y[i]);
}
for (int i = 1; i <= k; ++i) {
sort(v[i].begin(), v[i].end());
}
int idx = 1;
for (int i = 1; i <= k; ++i) {
int sz = v[i].size();
for (int j = 0; j < sz; ++j) {
set<int> prev;
int cur = 1;
mp[{i, v[i][j]}] = idx;
prev.insert(mp[{i-1, v[i][j]}]);
while (j != sz-1 && v[i][j+1] == v[i][j] + 1) {
cur++; j++;
prev.insert(mp[{i-1, v[i][j]}]);
mp[{i, v[i][j]}] = idx;
}
val[idx] = cur;
for (auto p : prev){
if (p == 0) continue;
ed[p].pb(idx);
ed[idx].pb(p);
}
idx++;
}
}
}
void dfs(int v, int pr){
sm[v] = val[v];
for (auto x : ed[v]){
if (x == pr) continue;
dfs(x, v);
sm[v] += sm[x];
sm[v] %= m;
}
}
int calcDist(int n, int v, int pr){
int res = 0;
for (auto x : ed[v]){
if (x == pr) continue;
ll k = sm[x] * (n - sm[x]) % m;
res += (int)k;
res %= m;
res += calcDist(n, x, v);
res %= m;
}
return res;
}
int DistanceSum(int n, int *x, int *y) {
int mn_x = oo, mn_y = oo;
for (int i = 0; i < n; ++i) {
mn_x = min(mn_x, x[i]);
mn_y = min(mn_y, y[i]);
}
int mx_x = 0, mx_y = 0;
for (int i = 0; i < n; ++i) {
x[i] = x[i] - mn_x + 1;
y[i] = y[i] - mn_y + 1;
mx_x = max(x[i], mx_x);
mx_y = max(y[i], mx_y);
}
int ans = 0;
build_tree(n, mx_x, x, y);
dfs(1, -1);
ans += calcDist(n, 1, -1);
ans %= m;
build_tree(n, mx_y, y, x);
dfs(1, -1);
ans += calcDist(n, 1, -1);
ans %= m;
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... |