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;
const int Mod = 1e9, Nmax = 1e5 + 5;
typedef long long ll;
int n, x[Nmax], y[Nmax], A[2005][2005], d[2005][2005];
class AIB
{
ll a[Nmax]; int b[Nmax];
int ub(int x) { return (x&(-x)); }
public:
int query(int x)
{
ll sum1 = 0, sum2 = 0;
int cnt1 = 0, cnt2 = 0;
int i;
for(i=x; i; i-=ub(i))
sum1 += a[i], cnt1 += b[i];
for(i=n; i; i-=ub(i))
sum2 += a[i], cnt2 += b[i];
sum2 -= sum1, cnt2 -= cnt1;
sum1 = (ll) x * cnt1 - sum1;
sum2 = sum2 - (ll) x * cnt2;
return (sum1 + sum2) % Mod;
}
void update(int pos)
{
int i;
for(i=pos; i<=n; i+=ub(i))
a[i] += pos, b[i] ++;
}
} aib;
int solve1()
{
int i;
vector<int> p[Nmax];
for(i=0; i<n; ++i) p[x[i]].push_back(y[i]);
ll sumx = 0, cnt = 0, ans = 0;
for(i=1; i<=n; ++i)
for(auto it : p[i])
{
ans += aib.query(it);
ans %= Mod;
aib.update(it);
ans += (ll) i * cnt - sumx;
ans %= Mod;
++cnt; sumx += i;
}
return (int)ans;
}
void bfs(int x, int y)
{
queue< pair<int,int> > q;
q.push({x, y});
d[x][y] = 0;
while(q.size())
{
tie(x, y) = q.front();
q.pop();
if(A[x-1][y] && d[x-1][y] == -1)
{
d[x-1][y] = d[x][y] + 1;
q.push({x-1, y});
}
if(A[x+1][y] && d[x+1][y] == -1)
{
d[x+1][y] = d[x][y] + 1;
q.push({x+1, y});
}
if(A[x][y-1] && d[x][y-1] == -1)
{
d[x][y-1] = d[x][y] + 1;
q.push({x, y-1});
}
if(A[x][y+1] && d[x][y+1] == -1)
{
d[x][y+1] = d[x][y] + 1;
q.push({x, y+1});
}
}
}
int DistanceSum(int N, int *X, int *Y)
{
int i, j, xmin = 2e9, ymin = 2e9; n = N;
for(i=0; i<N; ++i)
{
x[i] = X[i];
y[i] = Y[i];
xmin = min(xmin, x[i]);
ymin = min(ymin, y[i]);
}
for(i=0; i<N; ++i)
x[i] -= xmin - 1, y[i] -= ymin - 1;
if(N > 2000)
return solve1();
// cerr << solve1() << '\n';
ll ans = 0;
for(i=0; i<n; ++i) A[x[i]][y[i]] = 1;
for(i=0; i<n; ++i)
{
for(j=0; j<n; ++j) d[x[j]][y[j]] = -1;
bfs(x[i], y[i]);
for(j=i+1; j<n; ++j) ans += d[x[j]][y[j]];
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... |