# Bzoj3631【JLOI2014】松鼠的新家

Solution

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
using namespace std;
const int maxn = 300005;
struct edge{
int x,y,next;
edge(){}
edge(int _x,int _y,int _nt): x(_x) , y(_y) , next(_nt){}
}e [maxn << 1];
int head[maxn] , tot = 0;
e[++tot] = edge( x , y , head[x] ); head[x] = tot;
e[++tot] = edge( y , x , head[y] ); head[y] = tot;
}
int top[maxn],p[maxn],siz[maxn],son[maxn],fa[maxn],dep[maxn];
int n,m,T;
int tag[maxn][2],a[maxn],c[maxn],s[maxn];
void DFS1(int x){
siz[x] = 1; son[x] = 0;
for(int y,i = head[x] ; i ; i = e[i].next ){
y = e[i].y;
if( dep[y] ) continue;
dep[y] = dep[x] + 1;
fa[y] = x;
DFS1( y );
siz[x] += siz[y];
if( siz[y] > siz[son[x]] ) son[x] = y;
}
}
void DFS2(int x,int chain){
p[x] = ++T; top[x] = chain;
if( son[x] ) DFS2( son[x] , chain );
for(int y,i = head[x] ; i ; i = e[i].next ){
y = e[i].y;
if( p[y] || y == son[x] ) continue;
DFS2( y , y );
}
}
int sum = 0;
void DFS3(int x){
sum += tag[x][0];
s[x] = sum;
sum -= tag[x][1];
if( son[x] ) DFS3(son[x]);
}
int main(){
scanf("%d",&n);
for(int i = 1 ; i <= n ; i++)scanf("%d",&a[i]);
for(int i = 2 ; i <= n ; i++) c[a[i]]++;
for(int x,y,i = 1 ; i <= n-1 ; i++){
scanf("%d%d",&x,&y);
}
dep[1]=1;
DFS1( 1 );
DFS2( 1 , 1 );
for(int x,y,i = 1 ; i <= n-1 ;i++){
x = a[i]; y = a[i+1];

while( top[x] != top[y] ){
if( dep[top[x]] < dep[top[y]] )swap( x, y );
tag[top[x]][0]++;
tag[x][1]++;
x = fa[top[x]];
}
if( dep[x] > dep[y] ) swap( x , y );
tag[x][0]++;
tag[y][1]++;
}
for(int i = 1 ; i <= n ; i++)
if( i == top[i] ) DFS3(i);
for(int i = 1 ; i <= n ; i++)
printf("%d\n",s[i]-c[i]);
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120