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 int long long
using namespace std;
vector<vector<int>> g,jump;
vector<int> dep;
struct DSU{
int n;
vector<int> to,sz,mx,val;
DSU(int _n):n(_n){
to.resize(n);
sz.resize(n,1);
val.resize(n);
mx.resize(n);
for(int i=0;i<n;i++){
to[i]=i;
mx[i]=i;
}
}
int fnd(int p){
if(to[p]==p) return p;
to[p]=fnd(to[p]);
return to[p];
}
void conn(int a,int b){
a=fnd(a);
b=fnd(b);
if(a==b) return;
if(sz[a]>sz[b]) swap(a,b);
to[a]=b;
sz[b]+=sz[a];
mx[b]=max(mx[b],mx[a]);
}
};
void dfs(int pre,int pos){
for(int i:g[pos]){
if(i==pre) continue;
dep[i]=dep[pos]+1;
jump[i][0]=pos;
dfs(pos,i);
}
}
int lca(int a,int b){
if(dep[a]<dep[b]) swap(a,b);
int dif=dep[a]-dep[b],c=0;
while(dif){
if(dif&1){
a=jump[a][c];
}
c++;
dif>>=1;
}
if(a==b) return a;
for(int i=20;i>=0;i--){
if(jump[a][i]!=jump[b][i]){
a=jump[a][i];
b=jump[b][i];
}
}
return jump[a][0];
}
int dis(int a,int b){
int c=lca(a,b);
return dep[a]+dep[b]-2*dep[c];
}
signed main(){
int n;
cin>>n;
g.resize(n);
jump.resize(n,vector<int>(21));
dep.resize(n);
vector<vector<int>> gg(n);
vector<int> v(n);
for(int &i:v){
cin>>i;
i--;
}
for(int i=0;i<n-1;i++){
int a,b;
cin>>a>>b;
a--;
b--;
a=v[a];
b=v[b];
g[a].push_back(b);
g[b].push_back(a);
gg[max(a,b)].push_back(min(a,b));
}
dfs(0,0);
for(int j=1;j<21;j++){
for(int i=0;i<n;i++){
jump[i][j]=jump[jump[i][j-1]][j-1];
}
}
DSU dsu(n);
for(int i=0;i<n;i++){
int tmp=0;
for(int j:gg[i]){
int a=dis(i,dsu.mx[dsu.fnd(j)])+dsu.val[dsu.fnd(j)];
if(a>tmp){
tmp=a;
}
dsu.conn(i,j);
}
dsu.val[dsu.fnd(i)]=tmp;
}
cout<<dsu.val[dsu.fnd(n-1)]<<endl;
}
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |