您的位置:首页 > 其它

洛谷P3258 [JLOI2014]松鼠的新家

2017-09-26 21:43 330 查看

P3258 [JLOI2014]松鼠的新家

题目描述

松鼠的新家是一棵树,前几天刚刚装修了新家,新家有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<iostream>
#include<cstdio>
#define maxn 300010
using namespace std;
int n,a[maxn];
int dep[maxn],sz[maxn],son[maxn],fa[maxn],top[maxn];
int num,head[maxn],w[maxn];
struct node{
int to,pre;
}e[maxn*2];
void Insert(int from,int to){
e[++num].to=to;
e[num].pre=head[from];
head[from]=num;
}
void dfs1(int now,int father){
fa[now]=father;dep[now]=dep[father]+1;
sz[now]=1;
for(int i=head[now];i;i=e[i].pre){
int to=e[i].to;
if(to==father)continue;
dfs1(to,now);
sz[now]+=sz[to];
if(!son[now]||sz[to]>=sz[son[now]])son[now]=to;
}
}
void dfs2(int now,int father){
top[now]=father;
if(son[now])dfs2(son[now],father);
for(int i=head[now];i;i=e[i].pre){
int to=e[i].to;
if(to==fa[now]||to==son[now])continue;
dfs2(to,to);
}
}
void dfs3(int now,int father){
for(int i=head[now];i;i=e[i].pre){
int to=e[i].to;
if(to==father)continue;
dfs3(to,now);
w[now]+=w[to];
}
}
int lca(int a,int b){
while(top[a]!=top[b]){
if(dep[top[a]]<dep[top[b]])swap(a,b);
a=fa[top[a]];
}
if(dep[a]>dep[b])swap(a,b);
return a;
}
int main(){
//freopen("Cola.txt","r",stdin);
scanf("%d",&n);
int x,y;
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
for(int i=1;i<n;i++){
scanf("%d%d",&x,&y);
Insert(x,y);Insert(y,x);
}
dfs1(1,0);
dfs2(1,1);
for(int i=2;i<=n;i++){
x=a[i-1],y=a[i];
int Lca=lca(x,y);
w[x]++;w[fa[y]]++;
w[Lca]--;w[fa[Lca]]--;
}
dfs3(1,1);
for(int i=1;i<=n;i++)printf("%d\n",w[i]);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: