HDU 3887 Counting Offspring (树状数组)

思路:对于每个结点深搜,先记录在搜索该结点前已经出现过的比该结点小的结点总数为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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值