# Bzoj3631 [jloi2014]松鼠的新家

Posted by yjjr's blog on February 6, 2018

Description

Input

Output

Sample Input

5

1 4 5 3 2

1 2

2 4

2 3

4 5

Sample Output

1

2

1

2

1

HINT

2<= n <=300000

Code

#include<iostream>
#include<iomanip>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include<cmath>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define mem(X,num) memset(x,num,sizeof x)
#define reg(x) for(int i=head[x];i;i=e[i].next)
#define LL long long
using namespace std;
{
LL f=1,x=0;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int maxn=3e5+6;
LL bin[21],n,cnt=0;
struct edge{int to,next;}e[maxn<<1];
void dfs(int x)
{
rep(i,1,19)
if(deep[x]>=bin[i])fa[x][i]=fa[fa[x][i-1]][i-1];else break;
reg(x)
if(e[i].to!=fa[x][0]){
deep[e[i].to]=deep[x]+1;
fa[e[i].to][0]=x;
dfs(e[i].to);
}
}
int lca(int x,int y)
{
if(deep[x]<deep[y])swap(x,y);
int t=deep[x]-deep[y];
rep(i,0,19)
if(bin[i]&t)x=fa[x][i];
dep(i,19,0)
if(fa[x][i]!=fa[y][i])x=fa[x][i],y=fa[y][i];
if(x==y)return x;
return fa[x][0];
}
void dp(int x)
{
reg(x)
if(e[i].to!=fa[x][0]){
dp(e[i].to);
f[x]+=f[e[i].to];
}
}
int main()
{
bin[0]=1;rep(i,1,20)bin[i]=bin[i-1]<<1;
rep(i,1,n-1){
}
dfs(a[1]);
rep(i,1,n-1){
int t=lca(a[i],a[i+1]);
f[a[i]]++,f[a[i+1]]++;
f[t]--,f[fa[t][0]]--;
}
dp(a[1]);
rep(i,2,n)f[a[i]]--;
rep(i,1,n)printf("%lld\n",f[i]);
return 0;
}