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;
struct union_find{
int par[100100],sz[100100];
void RS(){memset(par,0,sizeof par);for(auto&i:sz)i=1;}
union_find(){RS();}
int comp(int x){
return par[x]?par[x]=comp(par[x]):x;
}
void merge(int a,int b){
a=comp(a); b=comp(b);
if(a<b) swap(a,b);
if(a-b) par[a]=b,
sz[b]+=sz[a];
}
} UF;
int mod=1e9;
long long ANS;
vector<int>adj[100100];
set<int>adj2[100100];
map<pair<int,int>,int>S;
long long SZ[100100];
void dfs(int n,int p,int x){
for(auto i:adj2[n])
if(i-p)dfs(i,n,x),
SZ[n]+=SZ[i];
ANS+=SZ[n]*(x-SZ[n]);
}
int DistanceSum(int N, int *X, int *Y) {
int A=*min_element(Y,Y+N);
int B=*min_element(X,X+N);
for(int i=0;i<N;i++)
S[{X[i]-=B,Y[i]-=A}]=i+1;
for(int i=N;i;i--)
X[i]=X[i-1],Y[i]=Y[i-1];
for(int i=1;i<=N;i++){
if(S.count({X[i]-1,Y[i]}))
adj[i].push_back(S[{X[i]-1,Y[i]}]);
if(S.count({X[i]+1,Y[i]}))
adj[i].push_back(S[{X[i]+1,Y[i]}]);
if(S.count({X[i],Y[i]-1}))
adj[i].push_back(S[{X[i],Y[i]-1}]);
if(S.count({X[i],Y[i]+1}))
adj[i].push_back(S[{X[i],Y[i]+1}]);
}
for(int i=1;i<=N;i++)
for(auto x:adj[i])
if(X[x]==X[i])
UF.merge(x,i);
for(int i=1;i<=N;i++)
for(auto x:adj[i]) if(Y[x]==Y[i])
adj2[UF.comp(x)].insert(UF.comp(i));
for(int i=1;i<=N;i++)
SZ[i]=UF.sz[i];
dfs(1,0,N);
UF.RS();
for(int i=1;i<=N;i++)
adj2[i].clear(),swap(X[i],Y[i]);
for(int i=1;i<=N;i++)
for(auto x:adj[i])
if(X[x]==X[i])
UF.merge(x,i);
for(int i=1;i<=N;i++)
for(auto x:adj[i]) if(Y[x]==Y[i])
adj2[UF.comp(x)].insert(UF.comp(i));
for(int i=1;i<=N;i++)
SZ[i]=UF.sz[i];
dfs(1,0,N);
return ANS%mod;
}
# | 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... |