Submission #1266314

#TimeUsernameProblemLanguageResultExecution timeMemory
1266314PlayVoltzCat Exercise (JOI23_ho_t4)C++20
100 / 100
251 ms77156 KiB
#include <cstdio>
#include <stdio.h>
#include <stdbool.h>
#include <iostream>
#include <map>
#include <vector>
#include <climits>
#include <stack>
#include <string>
#include <queue>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <cctype>
#include <bitset>
#include <iomanip>
#include <cstring>
#include <numeric>
#include <cassert>
using namespace std;

#define int long long
#define pii pair<int, int>
#define mp make_pair
#define pb push_back
#define fi first
#define se second

int ans=0;
vector<int> dsu, id, rev, depth;
vector<vector<int> > graph, twok, graph2;

void dfs(int node, int par, int d){
	depth[node]=d;
	twok[node][0]=par;
	for (int i=1; i<20; ++i)twok[node][i]=twok[twok[node][i-1]][i-1];
	for (auto num:graph[node])if (num!=par)dfs(num, node, d+1);
}

int fp(int a){
	if (dsu[a]==-1)return a;
	return dsu[a]=fp(dsu[a]);
}

void merge(int a, int b){
	a=fp(a), b=fp(b);
	if (a==b)return;
	if (id[a]<id[b])swap(a, b);
	dsu[b]=a;
	graph2[a].pb(b);
}

int kth(int a, int k){
	for (int i=0; i<20; ++i)if (k&(1<<i))a=twok[a][i];
	return a;
}

int lca(int a, int b){
	if (depth[a]<depth[b])swap(a, b);
	int temp=a, temp2=b;
	a=kth(a, depth[a]-depth[b]);
	if (a==b)return depth[temp]-depth[temp2];
	for (int i=19; i>=0; --i)if (twok[a][i]!=twok[b][i])a=twok[a][i], b=twok[b][i];
	return depth[temp]+depth[temp2]-2*depth[twok[a][0]];
}

void dfs2(int node, int d){
	ans=max(ans, d);
	for (auto num:graph2[node])dfs2(num, d+lca(num, node));
}

int32_t main(){
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int n;
	cin>>n;
	dsu.resize(n+1, -1);
	id.resize(n+1);
	rev.resize(n+1);
	graph.resize(n+1);
	graph2.resize(n+1);
	depth.resize(n+1);
	twok.resize(n+1, vector<int>(20));
	for (int i=1; i<=n; ++i)cin>>id[i], rev[id[i]]=i;
	for (int i=1, a, b; i<n; ++i){
		cin>>a>>b;
		graph[a].pb(b);
		graph[b].pb(a);
	}
	dfs(1, 1, 0);
	for (int i=1; i<=n; ++i)for (auto num:graph[rev[i]])if (id[num]<i)merge(num, rev[i]);
	dfs2(rev[n], 0);
	cout<<ans;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...