遇上水题,好爽啊。
就将每一二进制位初始为0与1的最终情况暴力求出来,贪心一下就好了。
code:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;
struct trnode{
int dep,fa,top,son,tot,l,r,lc,rc,c,u;
}tr[600020];int ys[300010],s[300010],z=0,trlen=0;
int ans[300010];
struct node{
int y,next;
}a[600010];int len=0,last[300010];
int b[300010];
void ins(int x,int y)
{
a[++len].y=y;
a[len].next=last[x];last[x]=len;
}
int bt(int l,int r)
{
int x=++trlen;
tr[x].l=l;tr[x].r=r;tr[x].c=0;
tr[x].u=0;
if(l!=r)
{
int mid=(l+r)/2;
tr[x].lc=bt(l,mid);
tr[x].rc=bt(mid+1,r);
}
return x;
}
void update(int x)
{
int lc=tr[x].lc,rc=tr[x].rc;
tr[lc].c+=tr[x].c;tr[rc].c+=tr[x].c;
tr[x].c=0;
}
void change(int x,int l,int r)
{
if(tr[x].l==l&&tr[x].r==r)
{
tr[x].c+=1;
return;
}
if(tr[x].c!=0) update(x);
int mid=(tr[x].l+tr[x].r)/2,lc=tr[x].lc,rc=tr[x].rc;
if(r<=mid) change(lc,l,r);
else if(l>mid) change(rc,l,r);
else change(lc,l,mid),change(rc,mid+1,r);
}
void pre_node(int x,int fa)
{
tr[x].fa=fa;tr[x].dep=tr[fa].dep+1;tr[x].tot=1;
for(int i=last[x];i;i=a[i].next)
{
int y=a[i].y;
if(y==fa) continue;
pre_node(y,x);tr[x].tot+=tr[y].tot;
if(tr[tr[x].son].tot<tr[y].tot) tr[x].son=y;
}
}
void pre_edge(int x,int top)
{
ys[x]=++z;s[z]=x;tr[x].top=top;
if(tr[x].son!=0) pre_edge(tr[x].son,top);
for(int i=last[x];i;i=a[i].next)
{
int y=a[i].y;
if(y==tr[x].fa||y==tr[x].son) continue;
pre_edge(y,y);
}
}
void solve(int x,int y)
{
int tx=tr[x].top,ty=tr[y].top;
while(tx!=ty)
{
if(tr[tx].dep<tr[ty].dep) swap(x,y),swap(tx,ty);
change(1,ys[tx],ys[x]);
x=tr[tx].fa;tx=tr[x].top;
}
if(tr[x].dep<tr[y].dep) swap(x,y);
change(1,ys[y],ys[x]);
}
void print(int x)
{
if(tr[x].l==tr[x].r) ans[s[tr[x].l]]=tr[x].c;
else update(x),print(tr[x].lc),print(tr[x].rc);
}
int main()
{
int n;scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&b[i]);
for(int i=1;i<n;i++)
{
int x,y;scanf("%d %d",&x,&y);
ins(x,y);ins(y,x);
}
z=0;pre_node(1,0);pre_edge(1,1);bt(1,n);
for(int i=2;i<=n;i++) solve(b[i-1],b[i]);
print(1);
for(int i=1;i<=n;i++)
{
if(i!=b[1]) ans[i]--;
printf("%d\n",ans[i]);
}
}