P3258 [JLOI2014]松鼠的新家
倍增lca+树上差分,从叶子节点向根节点求前缀和,dfs求子树和即可,最后,把每次的起点和终点都。
#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<set>
#include<map>
#include<stack>
#include<cstring>
#define inf 2147483647
#define For(i,a,b) for(register int i=a;i<=b;i++)
#define p(a) putchar(a)
#define g() getchar()
//by war
//2017.11.8
using namespace std;
int f[][];
int a[],b[];
int deep[];
int change[];
bool vis[];
int lca;
int x,y;
int n;
struct node
{
int n;
node *next;
}*e[]; inline void in(register int &x)
{
int y=;
char c=g();x=;
while(c<''||c>'')
{
if(c=='-')
y=-;
c=g();
}
while(c<=''&&c>='')x=(x<<)+(x<<)+c-'',c=g();
x*=y;
}
inline void o(register int x)
{
if(x<)
{
p('-');
x=-x;
}
if(x>)o(x/);
p(x%+'');
} inline void push(register int x,register int y)
{
node *p;
p=new node();
p->n=y;
if(e[x]==NULL)
e[x]=p;
else
{
p->next=e[x]->next;
e[x]->next=p;
}
} inline void build(register int now)
{
deep[now]=deep[f[now][]]+;
for(register int i=;(<<i)<=n;i++)
f[now][i]=f[f[now][i-]][i-];
for(node *i=e[now];i!=NULL;i=i->next)
{
if(f[now][]!=i->n)
{
f[i->n][]=now;
build(i->n);
}
}
} inline int query(register int x,register int y)
{
if(deep[x]<deep[y])
swap(x,y);
int c=deep[x]-deep[y];
for(register int i=;(<<i)<=c;i++)
if((<<i)&c)
x=f[x][i];
if(x==y)
return x;
for(register int i=log2(deep[x]);i>=;i--)
{
if(f[x][i]!=f[y][i])
{
x=f[x][i];
y=f[y][i];
}
}
return f[x][];
} int dfs(int now)
{
if(vis[now])
return b[now];
vis[now]=true;
for(node *i=e[now];i!=NULL;i=i->next)
if(!vis[i->n])
{
x=dfs(i->n);
b[now]+=x;
}
return b[now];
} int main()
{
// freopen("t.in","r",stdin);
// freopen("t2.out","w",stdout);
in(n);
For(i,,n)
in(a[i]);
For(i,,n-)
{
in(x),in(y);
push(x,y);
push(y,x);
}
// f[0][0]=0;
build();
For(i,,n-)
{
x=a[i];
y=a[i+];
lca=query(x,y);
change[x]++;
change[y]++;
change[lca]--;
change[f[lca][]]--;
}
For(i,,n)
b[i]=change[i];
b[]=dfs();
For(i,,n)
b[a[i]]--;
For(i,,n)
o(b[i]),p('\n');
return ;
}