# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
737315 | nguyentunglam | Cat Exercise (JOI23_ho_t4) | C++17 | 236 ms | 42800 KiB |
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 fi first
#define se second
#define endl "\n"
#define ii pair<int, int>
using namespace std;
const int N = 2e5 + 10;
int par[20][N], h[N], p[N], pos[N], lab[N], f[N];
vector<int> adj[N];
void dfs(int u) {
for(int j = 1; j <= 18; j++) par[j][u] = par[j - 1][par[j - 1][u]];
for(int &v : adj[u]) if (v != par[0][u]) {
par[0][v] = u; h[v] = h[u] + 1;
dfs(v);
}
}
int lca(int u, int v) {
if (h[u] < h[v]) swap(u, v);
int delta = h[u] - h[v];
for(int j = 18; j >= 0; j--) if (delta >> j & 1) u = par[j][u];
if (u == v) return u;
for(int j = 18; j >= 0; j--) if (par[j][u] != par[j][v]) {
u = par[j][u];
v = par[j][v];
}
return par[0][u];
}
int dist(int u, int v) {
return h[u] + h[v] - 2 * h[lca(u, v)];
}
int root(int v) {
return lab[v] == v ? v : lab[v] = root(lab[v]);
}
int main() {
#define task ""
cin.tie(0) -> sync_with_stdio(0);
if (fopen ("task.inp", "r")) {
freopen ("task.inp", "r", stdin);
freopen ("task.out", "w", stdout);
}
if (fopen (task".inp", "r")) {
freopen (task".inp", "r", stdin);
freopen (task".out", "w", stdout);
}
int n; cin >> n;
for(int i = 1; i <= n; i++) cin >> p[i], pos[p[i]] = i;
for(int i = 1; i < n; i++) {
int a, b; cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
dfs(1);
for(int i = 1; i <= n; i++) lab[i] = i;
for(int i = 1; i <= n; i++) {
int u = pos[i];
for(int &v : adj[u]) if (p[v] < i) {
int ver = root(v);
f[u] = max(f[u], f[ver] + dist(u, ver));
}
for(int &v : adj[u]) if (p[v] < i) {
int ver = root(v);
lab[ver] = u;
}
}
cout << f[pos[n]];
}
Compilation message (stderr)
# | 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... |