結果

問題 No.2634 Tree Distance 3
ユーザー 👑 potato167
提出日時 2024-02-13 16:02:13
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 644 ms / 3,000 ms
コード長 1,832 bytes
コンパイル時間 2,406 ms
コンパイル使用メモリ 206,552 KB
最終ジャッジ日時 2025-02-19 05:55:39
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 69
権限があれば一括ダウンロードができます

ソースコード

diff #

#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(){
	int N;
	cin>>N;
	vector<int> A(N);
	rep(i,0,N) cin>>A[i];
	vector<int> order(N);
	rep(i,0,N) order[i]=i;
	sort(all(order),[&](int l,int r){
		return A[l]>A[r];
	});
	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);
	}
	int B=0;
	while((1<<B)<N) B++;
	B++;
	vector<int> ans(N);
	vector<int> depth(N,-1);
	vector<int> E(N*2);
	vector table(B,vector<int>(N*2));
	int ind=0;
	auto dfs=[&](auto self,int var) -> void {
		E[var]=ind++;
		for(auto x:G[var]){
			if(depth[x]==-1){
				depth[x]=depth[var]+1;
				self(self,x);
			}
		}
		E[var+N]=ind++;
	};
	depth[0]=0;
	dfs(dfs,0);
	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> X(3);
	auto f=[&](int l1,int r1,int l2,int r2) -> void {
		X[0]=order[l1];
		rep(i,0,2){
			int tmp=-1,tmp2=0;
			rep(j,l1,r1){
				tmp2=dist(order[j],X[i]);
				if(tmp<tmp2) tmp=tmp2,X[i+1]=order[j];
			}
		}
		rep(i,l2,r2) rep(j,1,3) chmax(ans[order[i]],dist(order[i],X[j]));
	};
	
	int L=0,R=0;
	while(L<N){
		while(R!=N&&A[order[L]]==A[order[R]]) R++;
		f(L,R,L,R);
		L=R;
	}
	
	rep(d,0,B-1){
		L=0;
		int M;
		while(L<N){
			M=min(N,L+(1<<d));
			R=min(N,M+(1<<d));
			f(L,M,M,R);
			L=R;
		}
	}
	rep(i,0,N){
		if(i) cout<<" ";
		cout<<ans[i];
	}
	cout<<"\n";
}
0