BZOJ3631[JLOI2014]松鼠的新家 题解

时间:2023-11-15 12:11:56

题目大意:

  给你一棵树,要从编号为a[1]的节点走到编号为a[2]的节点再走到编号为a[3]的节点……一直走到编号为a[n]的节点。问每个节点最少访问多少次。

思路:

  将其进行轻重链剖分,则从a[i]走到a[i+1]实际上就是在几段重链的节点上+1,于是就用线段树来维护一下即可。

代码:

 #include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define M 1200000
using namespace std; int ans[M],to[M],head[M],next[M],vis[M],size[M],deep[M],id[M],top[M],sum[M],fa[M],a[M],cnt,dfn,n; void add(int x,int y)
{
to[++cnt]=y;
next[cnt]=head[x];
head[x]=cnt;
} void dfs1(int x)
{
size[x]=vis[x]=;
for (int i=head[x];i;i=next[i])
if (!vis[to[i]])
{
deep[to[i]]=deep[x]+;
fa[to[i]]=x;
dfs1(to[i]);
size[x]+=size[to[i]];
}
} void dfs2(int x,int chain)
{
int k=,i;
id[x]=++dfn;
top[x]=chain;
for (i=head[x];i;i=next[i])
if (deep[to[i]]>deep[x] && size[to[i]]>size[k]) k=to[i];
if (!k) return;
dfs2(k,chain);
for (i=head[x];i;i=next[i])
if (deep[to[i]]>deep[x] && to[i]!=k) dfs2(to[i],to[i]);
} void push_down(int cur)
{
sum[cur<<]+=sum[cur];
sum[cur<<|]+=sum[cur];
sum[cur]=;
} void ADD(int L,int R,int l,int r,int cur)
{
if (l<=L && r>=R)
{
sum[cur]++;
return;
}
push_down(cur);
int mid=L+R>>;
if (l>mid) ADD(mid+,R,l,r,cur<<|);
else if (r<=mid) ADD(L,mid,l,r,cur<<);
else ADD(L,mid,l,mid,cur<<),ADD(mid+,R,mid+,r,cur<<|);
} int ask(int l,int r,int x,int cur)
{
if (l==r) return sum[cur];
push_down(cur);
int mid=l+r>>;
if (x>mid) return sum[cur]+ask(mid+,r,x,cur<<|);
else return sum[cur]+ask(l,mid,x,cur<<);
} void Add(int x,int y)
{
for (;top[x]!=top[y];x=fa[top[x]])
{
if (deep[top[x]]<deep[top[y]]) swap(x,y);
ADD(,n,id[top[x]],id[x],);
}
if (deep[x]<deep[y]) swap(x,y);
ADD(,n,id[y],id[x],);
} int main()
{
int i,x,y;
scanf("%d",&n);
for (i=;i<=n;i++) scanf("%d",&a[i]);
for (i=;i<n;i++) scanf("%d%d",&x,&y),add(x,y),add(y,x);
dfs1();
dfs2(,);
for (i=;i<n;i++) Add(a[i],a[i+]);
for (i=;i<=n;i++)
{
ans[i]=-(i!=a[]);
ans[i]+=ask(,n,id[i],);
}
for (i=;i<=n;i++) printf("%d\n",ans[i]);
return ;
}