bzoj3631 松鼠的新家
Description
松鼠的新家是一棵树,前几天刚刚装修了新家,新家有n个房间,并且有n-1根树枝连接,每个房间都可以相互到达,且俩个房间之间的路线都是唯一的。天哪,他居然真的住在“树”上。松鼠想邀请****前来参观,并且还指定一份参观指南,他希望**能够按照他的指南顺序,先去a1,再去a2,……,最后到an,去参观新家。
可是这样会导致**重复走很多房间,懒惰的**不听地推辞。可是松鼠告诉他,每走到一个房间,他就可以从房间拿一块糖果吃。**是个馋家伙,立马就答应了。
现在松鼠希望知道为了保证**有糖果吃,他需要在每一个房间各放至少多少个糖果。因为松鼠参观指南上的最后一个房间an是餐厅,餐厅里他准备了丰盛的大餐,所以当**在参观的最后到达餐厅时就不需要再拿糖果吃了。
Input
第一行一个整数n,表示房间个数
第二行n个整数,依次描述a1-an
接下来n-1行,每行两个整数x,y,表示标号x和y的两个房间之间有树枝相连。
Output
一共n行,第i行输出标号为i的房间至少需要放多少个糖果,才能让**有糖果吃。
Sample Input
5
1 4 5 3 2
1 2
2 4
2 3
4 5
1 4 5 3 2
1 2
2 4
2 3
4 5
Sample Output
1
2
1
2
1
2
1
2
1
HINT
2<= n <=300000
可以树剖,也可以不用。
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
using namespace std;
const int maxn=3e5+10;
int n,a[maxn],maxd,mi[21],ans[maxn];
int aa;char cc;
int read() {
aa=0;cc=getchar();
while(cc<'0'||cc>'9') cc=getchar();
while(cc>='0'&&cc<='9') aa=aa*10+cc-'0',cc=getchar();
return aa;
}
int fir[maxn],nxt[2*maxn],to[2*maxn],e=0;
void add(int x,int y) {
to[++e]=y;nxt[e]=fir[x];fir[x]=e;
to[++e]=x;nxt[e]=fir[y];fir[y]=e;
}
int fa[maxn][21],dep[maxn];
void dfs1(int pos,int d) {
maxd=max(maxd,d);dep[pos]=d;
for(int y=fir[pos];y;y=nxt[y]) {
if(to[y]==fa[pos][0]) continue;
fa[to[y]][0]=pos;dfs1(to[y],d+1);
}
}
int getlca(int x,int y) {
if(dep[x]!=dep[y]) {
int cha=dep[x]-dep[y];
for(int i=20;i>=0&&cha;--i) if(cha>=mi[i]){
cha-=mi[i]; x=fa[x][i];
}
}
int xx,yy,d=0;
while(x!=y) {
xx=x;yy=y;d=0;
while(xx!=yy) {
x=xx;y=yy;
xx=fa[xx][d];yy=fa[yy][d];
d++;
}
if(d==1) x=xx,y=yy;
}
return x;
}
void dfs2(int pos) {
for(int y=fir[pos];y;y=nxt[y]) {
if(to[y]==fa[pos][0]) continue;
dfs2(to[y]); ans[pos]+=ans[to[y]];
}
}
int main() {
n=read();int x,y;
for(int i=1;i<=n;++i) a[i]=read();
for(int i=1;i<n;++i) {
x=read(); y=read();
add(x,y);
}
dfs1(1,0);
mi[0]=1;for(int i=1;i<=20;++i) mi[i]=mi[i-1]<<1;
for(int i=1;i<=20;++i) for(int j=1;j<=n;++j) fa[j][i]=fa[fa[j][i-1]][i-1];
for(int i=1;i<n;++i) {
x=a[i];y=a[i+1];
if(dep[x]<dep[y]) swap(x,y);
int LCA=getlca(x,y);
ans[LCA]--;ans[fa[LCA][0]]--;
ans[a[i]]++;ans[fa[a[i+1]][0]]++;
}
dfs2(1);
for(int i=1;i<=n;++i) printf("%d\n",ans[i]);
return 0;
}
弱者就是会被欺负呀

浙公网安备 33010602011771号