結果
| 問題 |
No.2634 Tree Distance 3
|
| コンテスト | |
| ユーザー |
👑 potato167
|
| 提出日時 | 2024-02-14 11:57:26 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 259 ms / 3,000 ms |
| コード長 | 1,715 bytes |
| コンパイル時間 | 2,284 ms |
| コンパイル使用メモリ | 209,440 KB |
| 最終ジャッジ日時 | 2025-02-19 12:59:36 |
|
ジャッジサーバーID (参考情報) |
judge3 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 69 |
ソースコード
#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=int(a);i<int(b);i++)
#define all(p) p.begin(),p.end()
void chmin(int &a,int b){a=min(a,b);}
void chmax(int &a,int b){a=max(a,b);}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N;
cin>>N;
vector<int> A(N);
rep(i,0,N) cin>>A[i];
vector<vector<int>> G(N);
rep(i,0,N-1){
int a,b;
cin>>a>>b;
a--,b--;
G[a].push_back(b);
G[b].push_back(a);
}
vector<int> ans(N);
vector<int> depth(N,-1);
vector<int> E(N*2);
stack<int> st;
st.push(0);
depth[0]=0;
rep(i,0,2*N){
int a=st.top();
st.pop();
E[a]=i;
if(a<N){
st.push(a+N);
for(auto x:G[a]){
if(depth[x]==-1){
depth[x]=depth[a]+1;
st.push(x);
}
}
}
}
int B=0;
while((1<<B)<N) B++;
B++;
vector table(B,vector<int>(N*2));
rep(i,0,N){
table[0][E[i]]=depth[i];
table[0][E[i+N]]=depth[i]-1;
}
rep(i,0,B-1) rep(j,0,N*2){
table[i+1][j]=table[i][j];
if(j+(1<<i)<N*2) chmin(table[i+1][j],table[i][j+(1<<i)]);
}
auto dist=[&](int a,int b) -> int {
if(E[a]>E[b]) swap(a,b);
int l=E[a];
int r=E[b]+1;
int z=31-__builtin_clz(r-l);
return depth[a]+depth[b]-2*min(table[z][l],table[z][r-(1<<z)]);
};
vector<int> order(N);
rep(i,0,N) order[i]=i;
sort(all(order),[&](int l,int r){
return A[l]>A[r];
});
int L=0,R=0;
int X=order[0],Y=order[0],D=0;
while(L<N){
while(R<N&&A[order[L]]==A[order[R]]){
int tmpX=dist(X,order[R]);
int tmpY=dist(Y,order[R]);
if(tmpX<tmpY) swap(X,Y),swap(tmpX,tmpY);
if(D<tmpX) D=tmpX,Y=order[R];
R++;
}
rep(i,L,R){
ans[order[i]]=max(dist(order[i],X),dist(order[i],Y));
}
L=R;
}
rep(i,0,N){
if(i) cout<<" ";
cout<<ans[i];
}
cout<<"\n";
}
potato167