题目描述
松鼠的新家是一棵树,前几天刚刚装修了新家,新家有n个房间,并且有n-1根树枝连接,每个房间都可以相互到达,且俩个房间之间的路线都是唯一的。天哪,他居然真的住在”树“上。
松鼠想邀请小熊维尼前来参观,并且还指定一份参观指南,他希望维尼能够按照他的指南顺序,先去a1,再去a2,......,最后到an,去参观新家。可是这样会导致维尼重复走很多房间,懒惰的维尼不停地推辞。可是松鼠告诉他,每走到一个房间,他就可以从房间拿一块糖果吃。
维尼是个馋家伙,立马就答应了。现在松鼠希望知道为了保证维尼有糖果吃,他需要在每一个房间各放至少多少个糖果。
因为松鼠参观指南上的最后一个房间an是餐厅,餐厅里他准备了丰盛的大餐,所以当维尼在参观的最后到达餐厅时就不需要再拿糖果吃了
输入格式:
第一行一个整数n,表示房间个数第二行n个整数,依次描述a1-an
接下来n-1行,每行两个整数x,y,表示标号x和y的两个房间之间有树枝相连。
输出格式:
一共n行,第i行输出标号为i的房间至少需要放多少个糖果,才能让维尼有糖果吃。
输入样例#1:
5 1 4 5 3 2 1 2 2 4 2 3 4 5
输出样例#1:
1 2 1 2 1
2<= n <=300000
好裸的树上差分
#include<bits/stdc++.h>
#define N 300005
using namespace std;
int first[N],next[N*2],to[N*2],tot;
int n,m,a[N],ans[N];
int cnt[N],dep[N],fa[N][20];
int read(){
int cnt=0,f=1;char ch=0;
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch))cnt=cnt*10+(ch-'0'),ch=getchar();
return cnt*f;
}
void add(int x,int y){
next[++tot]=first[x],first[x]=tot,to[tot]=y;
}
void dfs(int u,int f){
for(int i=1;i<=18;i++)
fa[u][i]=fa[fa[u][i-1]][i-1];
for(int i=first[u];i;i=next[i]){
int t=to[i]; if(t==f) continue;
dep[t]=dep[u]+1,fa[t][0]=u;
dfs(t,u);
}
}
int lca(int x,int y){
if(dep[x]<dep[y])swap(x,y);
for(int i=18;i>=0;i--)
if(dep[fa[x][i]]>=dep[y])
x=fa[x][i];
if(x==y) return x;
for(int i=18;i>=0;i--)
if(fa[x][i]!=fa[y][i])
x=fa[x][i],y=fa[y][i];
return fa[x][0];
}
void dfs_ans(int u,int f){
ans[u]=cnt[u];
for(int i=first[u];i;i=next[i]){
int t=to[i]; if(t==f) continue;
dfs_ans(t,u); ans[u]+=ans[t];
}
}
int main(){
n=read();
for(int i=1;i<=n;i++) a[i]=read();
for(int i=1;i<n;i++){
int x=read(),y=read();
add(x,y),add(y,x);
}
dep[1]=1,dfs(1,0);
for(int i=1;i<=n-1;i++){
int x=a[i],y=a[i+1],l=lca(x,y);
cnt[x]++,cnt[y]++,cnt[l]--,cnt[fa[l][0]]--;
}
dfs_ans(1,0);
ans[a[1]]++;
for(int i=1;i<=n;i++)
printf("%d\n",ans[i]-1);
return 0;
return 0;
}