思路:对于每个结点深搜,先记录在搜索该结点前已经出现过的比该结点小的结点总数为pre[i],然后搜索并更新该结点的所有子树,最后返回该节点时,再求一次比该结点小的结点总数now[i],则该结点子树中比他小的结点总数就为now[i]-pre[i]。查询出现过比i小的结点总数用树状数组。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn=100005;
const int maxm=200005;
int c[maxn],n,p;
int head[maxn],to[maxm],next[maxm];
int ans[maxn],edge,tmp[maxn],stk[maxn],pre[maxn],now[maxn];
bool vis[maxn];
inline void addedge(int u,int v)
{
to[edge]=v,next[edge]=head[u],head[u]=edge++;
}
inline int lowbit(int x)
{
return x&-x;
}
void add(int x)
{
while(x<=n)
++c[x],x+=lowbit(x);
}
int sum(int x)
{
int s=0;
while(x>0)
s+=c[x],x-=lowbit(x);
return s;
}
void dfs(int root)
{
int top=0,i;
stk[top++]=root;
while(top)
{
int tmp=stk[top-1];
int f=top;
if(!vis[tmp]) {pre[tmp]=sum(tmp);vis[tmp]=1;}
for(i=head[tmp];~i;i=next[i])
if(!vis[to[i]])
stk[top++]=to[i];
if(f==top)
{
now[tmp]=sum(tmp);
ans[tmp]=now[tmp]-pre[tmp];
add(tmp);
top--;
}
}
}
int main()
{
int i,u,v;
while(~scanf("%d%d",&n,&p)&&(n&&p))
{
edge=0;
for(i=1; i<=n; ++i)
{
head[i]=-1;
c[i]=pre[i]=now[i]=0;
vis[i]=0;
}
for(i=0; i<n-1; ++i)
{
scanf("%d%d",&u,&v);
addedge(u,v);
addedge(v,u);
}
dfs(p);
for(i=1; i<=n; i++)
if(i==1) printf("%d",ans[i]);
else printf(" %d",ans[i]);
printf("\n");
}
return 0;
}