This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
/* Author : Mychecksdead */
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define MOD (1000000000+7)
#define MOD1 (998244353)
#define pb push_back
#define all(x) x.begin(), x.end()
#define en cout << '\n'
const int N = 1e6+100, M = 1e5+10, K = 52, MX = 30;
ll dp[N], dep[N];
int _lca(int u, int v);
struct Dsu{
vector<int> s, p, mx;
Dsu(int n){
s.resize(n+1, 1);
p.resize(n+1);
mx.resize(n+1);
for(int i = 1; i <= n; ++i) p[i] = i, mx[i] = i;
}
int find(int v){
if(p[v] == v) return v;
return p[v] = find(p[v]);
}
void merge(int a, int b){
int u = find(a);
int v = find(b); // b is the bigger vertex
if(u != v){
// cout << a << ' ' << b << ' ' <<mx[u] << '\n';
dp[b] = max(dp[b], dp[mx[u]] + dep[mx[u]] + dep[b] - 2 * dep[_lca(mx[u], b)]);
if(s[u] < s[v]) swap(u, v);
mx[u] = max(mx[v], mx[u]);
p[v] = u;
s[u] += s[v];
}
}
};
int n, a[N], timer=0, tin[N], tout[N], up[N][K];
vector<array<int, 2>> edges;
vector<int> g[N];
void dfs(int v, int p){
dep[v] = dep[p] + 1;
up[v][0] = p;
tin[v] = timer++;
for(int u: g[v]) if(u != p) dfs(u, v);
tout[v] = timer++;
}
bool is(int u, int v){
return tin[u] <= tin[v] && tout[v] <= tout[u];
}
int _lca(int u, int v){
if(is(u, v)) return u;
if(is(v, u)) return v;
for(int j = K-1; j >= 0; --j) if(!is(up[u][j], v)) u = up[u][j];
return up[u][0];
}
void solve(){
cin >> n;
for(int i = 1; i <= n; ++i) cin >> a[i];
for(int i = 0; i < n-1; ++i){
int u, v; cin >> u >> v;
u = a[u], v = a[v];
g[u].pb(v);
g[v].pb(u);
edges.pb({max(u, v), min(u, v)});
}
sort(all(edges));
dep[1] = 0;
dfs(1, 1);
for(int j = 1; j < K; ++j) for(int i = 1; i <= n; ++i) up[i][j] = up[up[i][j - 1]][j - 1];
Dsu d(n);
for(auto e: edges){
int u = e[0], v = e[1];
// cout << u << ' ' << v << '\n';
d.merge(v, u);
}
// for(int i = 1; i <= n; ++i) cout << dp[i] << ' ';
cout << dp[n];
}
int main(){
cin.tie(0); ios::sync_with_stdio(0);
int tt = 1, aa;
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
// cin >> tt;
while(tt--){
solve();
en;
}
cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" seconds\n";
return 0;
}
Compilation message (stderr)
Main.cpp: In function 'int main()':
Main.cpp:96:15: warning: unused variable 'aa' [-Wunused-variable]
96 | int tt = 1, aa;
| ^~
# | 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... |