結果

問題 No.2634 Tree Distance 3
ユーザー noya2
提出日時 2024-02-16 16:47:57
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
TLE  
実行時間 -
コード長 1,810 bytes
コンパイル時間 3,010 ms
コンパイル使用メモリ 256,376 KB
実行使用メモリ 28,796 KB
最終ジャッジ日時 2024-09-28 19:30:58
合計ジャッジ時間 12,136 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample -- * 2
other AC * 16 TLE * 1 -- * 52
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
using namespace std;

template<typename T>
bool chmax(T &a, const T &b){
    if (a >= b) return false;
    a = b;
    return true;
}

void input(int &x){
    char c;
    x = 0;
    while ((c = getchar_unlocked() ^ 48) < 10){
        x *= 10;
        x += c;
    }
}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    int n; input(n);
    vector<int> a(n);
    for (auto &x : a) input(x);
    vector<vector<int>> g(n);
    for (int i = 0; i < n-1; i++){
        int u, v; input(u), input(v); u--, v--;
        g[u].emplace_back(v);
        g[v].emplace_back(u);
    }
    vector<int> ids(n); iota(ids.begin(),ids.end(),0);
    sort(ids.begin(),ids.end(),[&](int l, int r){
        return a[l] > a[r];
    });
    vector<int> dmax(n,0);
    vector<int> from(n,-1);
    auto dfs_update = [&](auto sfs, int v, int f) -> void {
        for (int u : g[v]){
            if (u == f) continue;
            dmax[u] = dmax[v]+1;
            from[u] = v;
            sfs(sfs,u,v);
        }
    };
    dfs_update(dfs_update,ids[0],-1);
    auto dfs = [&](auto sfs, int v, int f, int d) -> void {
        int u = from[v];
        if (u == f) return ;
        assert(u != -1);
        if (chmax(dmax[u],d+1)){
            from[u] = v;
            dfs_update(dfs_update,u,v);
        }
        else {
            sfs(sfs,u,v,d+1);
        }
    };
    vector<int> ans(n);
    for (int l = 0, r = 0; l < n; l = r){
        while (r < n && a[ids[r]] == a[ids[l]]){
            if (r != 0){
                dfs(dfs,ids[r],-1,0);
            }
            r++;
        }
        for (int i = l; i < r; i++){
            ans[ids[i]] = dmax[ids[i]];
        }
    }
    for (int i = 0; i < n; i++){
        if (i != 0) cout << ' ';
        cout << ans[i];
    }
    cout << '\n';
}
0