Submission #937793

#TimeUsernameProblemLanguageResultExecution timeMemory
937793weakweakweakCat Exercise (JOI23_ho_t4)C++14
100 / 100
203 ms46864 KiB
#include <bits/stdc++.h>
using namespace std;

int n, val[210000], fa[210000], vtoi[210000], par[210000][21], dep[210000] = {0};
long long ans[210000] = {0};
vector <int> e[210000];

int find (int x) {return fa[x] == x ? x : fa[x] = find(fa[x]);}

void dfs(int i, int p) {
    dep[i] = dep[p] + 1;
    par[i][0] = p;
    for (int j : e[i]) if (j != p) dfs(j, i);
}

int dis (int x, int y) {
    int res = 0;
    if (dep[x] > dep[y]) swap(x, y);
    for (int i = 0; i <= 19; i++) if ((dep[y] - dep[x]) & (1 << i)) y = par[y][i], res += (1 << i);
    if (x == y) return res;
    for (int j = 19; j >= 0; j--) if (par[x][j] != par[y][j]) x = par[x][j], y = par[y][j], res += (1 << j) << 1;
    res += 2;
return res;}


int main () {
    //輸入、建圖
    ios_base::sync_with_stdio(false); cin.tie(0);
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> val[i];
        vtoi[val[i]] = i, fa[i] = i;
    }
    for (int i = 1; i < n; i++) {
        int x, y;
        cin >> x >> y;
        e[x].push_back(y);
        e[y].push_back(x);
    }

    //初始化lca 
    dfs(1, 1);
    for (int j = 1; j <= 19; j++) for (int i = 1; i <= n; i++) par[i][j] = par[par[i][j - 1]][j - 1];

    //做事(反著作回來,原本的操作是拔值最大的點,然後選一個子樹進去做一樣的事。現在反著做就變加點了)
    for (int ii = 1; ii <= n; ii++) {
        int i = vtoi[ii];
        for (int j : e[i]) {
            if (val[j] > ii) continue;
            j = find(j);
            ans[i] = max(ans[i], ans[j] + dis(j, i));
            fa[j] = i;      
        }
    }

    cout << ans[vtoi[n]] << '\n';
return 0;}
#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...