开大了 MLE ,开小了 WA。
#include<bits/stdc++.h>
#define int long long
using namespace std;char eof_flag;inline char read(int*s){if(eof_flag)return 0;int k=0,f=1;char c=getchar();while(c!='-'&&(c<'0'||c>'9')){if(c==EOF){eof_flag=1;return 0;}c=getchar();}f=(c=='-')?-1:1;k=(c=='-')?0:(c^48);c=getchar();while(c>='0'&&c<='9')k=(k<<1)+(k<<3)+(c^48),c=getchar();if(c==EOF)eof_flag=1;(*s)=f>0?k:-k;return 1;}
inline void write(int x){if(x<0)putchar('-'),x=-x;if(x>9)write(x/10);putchar(x%10+'0');return;}
const int N=1e5+10;
struct node {int l,r,maxx,ans,ls,rs;}t[N*50];
int n,pos[N],cnt,root[N],ans[N],top;
vector<int> e[N];
inline void push_up(int u)
{
int lson=t[u].ls,rson=t[u].rs;
if (t[lson].maxx>t[rson].maxx)
{
t[u].maxx=t[lson].maxx;
t[u].ans=t[lson].ans;
}
else if (t[lson].maxx<t[rson].maxx)
{
t[u].maxx=t[rson].maxx;
t[u].ans=t[rson].ans;
}
else
{
t[u].maxx=t[u].maxx;
t[u].ans=t[lson].ans+t[rson].ans;
}
return ;
}
inline void update(int &u,int l,int r,int x)
{
if (!u) u=++cnt;
if (l==r)
{
t[u].maxx++;
t[u].ans=l;
return ;
}
int mid=l+r>>1;
if (x<=mid) update(t[u].ls,l,mid,x);
else update(t[u].rs,mid+1,r,x);
push_up(u);
return ;
}
inline int merge(int u,int v,int l,int r)
{
if (!u or !v) return u+v;
if (l==r)
{
t[u].maxx+=t[v].maxx;
t[u].ans=l;
return u;
}
int mid=l+r>>1;
t[u].ls=merge(t[u].ls,t[v].ls,l,mid);
t[u].rs=merge(t[u].rs,t[v].rs,mid+1,r);
push_up(u);
return u;
}
inline void dfs(int u,int fa)
{
for (auto v : e[u])
{
if (v==fa) continue;
dfs(v,u);
root[u]=merge(root[u],root[v],1,n);
}
update(root[u],1,n,pos[u]);
ans[u]=t[root[u]].ans;
return ;
}
signed main()
{
read(&n);
for (int i=1;i<=n;i++) read(pos+i),root[i]=i,cnt++;
for (int i=1;i<=n-1;i++)
{
int u,v;
read(&u),read(&v);
e[u].push_back(v);
e[v].push_back(u);
}
dfs(1,0);
for (int i=1;i<=n;i++) cout<<ans[i]<<' ';
return 0;
}