This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
// High above the clouds there is a rainbow...
#include<bits/stdc++.h>
#define F first
#define S second
#define PB push_back
#define sz(s) int((s).size())
#define bit(n,k) (((n)>>(k))&1)
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
const int maxn=1e5+10,SQ=350;
int a[maxn],fn[maxn],par[maxn],state[maxn],arr[maxn],A[maxn],B[maxn],C;
vector<int>v[maxn];
pii p[SQ+10];
void add(int pos,int x){
for(pos=pos+3;pos<maxn;pos+=(pos & -pos))
fn[pos]+=x;
}
int ask(int pos){
int ans=0;
for(pos=pos+3;pos>0;pos-=(pos & -pos))
ans+=fn[pos];
return ans;
}
int sp[20][2*maxn],h[maxn],start[maxn];
vector<int>vec;
void dfs(int u){
if(par[u]!=-1) h[u]=h[par[u]]+1;
start[u]=sz(vec), vec.PB(u);
for(int i=1;i<20;i++){
sp[i][u]=sp[i-1][u];
if(sp[i][u]!=-1) sp[i][u]=sp[i-1][sp[i-1][u]];
}
for(int y:v[u]){
dfs(y);
}
if(par[u]!=-1) vec.PB(par[u]);
}
void prep(){
for(int i=0;i<sz(vec);i++){
sp[0][i]=h[vec[i]];
}
for(int i=1;i<20;i++){
for(int j=0;j<sz(vec);j++){
sp[i][j]=sp[i-1][j];
if(j+(1<<(i-1))<sz(vec)) sp[i][j]=min(sp[i][j],sp[i-1][j+(1<<(i-1))]);
}
}
}
int lca(int a,int b){
a=start[a], b=start[b];
if(a>b) swap(a,b);
int id=31-__builtin_clz(b-a+1);
return min(sp[id][a],sp[id][b+1-(1<<id)]);
}
int main(){
ios_base::sync_with_stdio(false);cin.tie(0);
int n;cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
arr[i]=a[i];
}
sort(arr,arr+n);
C=unique(arr,arr+n)-arr;
for(int i=0;i<n;i++){
a[i]=lower_bound(arr,arr+C,a[i])-arr;
}
par[0]=-1;
for(int i=0;i<n-1;i++){
cin>>A[i]>>B[i];
par[--B[i]]=--A[i];
v[A[i]].PB(B[i]);
}
dfs(0);
prep();
for(int l=0;l<n-1;l+=SQ){
int r=min(n-1,l+SQ);
++C;
for(int i=l;i<r;i++){
ll ans=0;
int x=A[i],lst=x;
state[B[i]]=C;
while(x>=0 && state[x]!=C){
state[x]=C;
ans+=ask(a[x]-1);
add(a[x],1);
lst=x=par[x];
}
int bh=-1,SZ=0;
for(int j=i-1;j>=l;j--){
int hh=lca(A[i],B[j]);
if(bh<hh) p[SZ++]={hh-bh,a[B[j]]}, bh=hh;
}
for(int j=SZ-1;j>=0;j--){
ans+= 1ll*p[j].F * ask(p[j].S-1);
add(p[j].S,p[j].F);
}
x=A[i];
while(x!=lst){
add(a[x],-1);
x=par[x];
}
for(int j=0;j<SZ;j++){
add(p[j].S,-p[j].F);
}
cout<<ans<<"\n";
}
++C;
for(int i=r-1;i>=l;i--){
int x=B[i];
while(x>=0 && state[x]!=C){
state[x]=C;
a[x]=a[B[i]];
x=par[x];
}
}
}
return 0;
}
// Deathly mistakes:
// * Read the problem curfully.
// * Check maxn.
// * Overflows.
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |