이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
#define INF 1e18
using namespace std;
typedef long long ll;
vector<int>adj[2000005];
ll d[2000005],par[2000005], p[2000005][25], dp[2000005];
void dfs(int s, int e) {
for (int i = 1; i <=20; i++) {
p[s][i] = p[p[s][i - 1]][i - 1];
}
for (auto u : adj[s]) {
if (u == e) continue;
d[u] = d[s] + 1;
p[u][0] = s;
dfs(u, s);
}
}
int lca(int a, int b) {
if (d[a] > d[b]) swap(a, b);
int dist = d[b] - d[a];
for (int i = 0; i <= 20; i++) {
if (dist & (1 << i))b = p[b][i];
}
if (a == b) return a;
for (int i = 20; i >= 0; i--) {
if (p[a][i] != p[b][i]) {
a = p[a][i];
b = p[b][i];
}
}
return p[a][0];
}
int find(int x) {
while (x != par[x])x = par[x];
return x;
}
int get_dist(int a, int b) {
int lcaa = lca(a, b);
return (d[a] - d[lcaa]) + (d[b] - d[lcaa]);
}
void solve()
{
int n; cin >> n;
vector<int>v(n + 1);
for (int i = 1; i <= n; i++) cin >> v[i];
for (int i = 1; i <= n - 1; i++) {
int a, b; cin >> a >> b;
a = v[a]; b = v[b];
adj[a].push_back(b);
adj[b].push_back(a);
}
dfs(1, 0);
for (int i = 1; i <= n; i++) par[i] = i;
for (int i = 1; i <= n; i++) {
for (auto u : adj[i]) {
u = find(u);
if (u < i) {
par[u] = i;
dp[i] = max(dp[i], dp[u] + get_dist(i, u));
}
}
}
cout << dp[n] << "\n";
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int t = 1;// cin>>t;
while (t--) solve();
return 0;
}
# | 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... |