HDU 3887 Counting Offspring (树状数组+dfs)

Counting Offspring

Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2688 Accepted Submission(s): 926

Problem Description
You are given a tree, it’s root is p, and the node is numbered from 1 to n. Now define f(i) as the number of nodes whose number is less than i in all the succeeding nodes of node i. Now we need to calculate f(i) for any possible i.

Input
Multiple cases (no more than 10), for each case:
The first line contains two integers n (0

#include "cstring"
#include "cstdio"
#include "iostream"
using namespace std;
#define E 100005
struct edge
{
    int to, next;
}Edge[2*E];
int head[2*E],e;
int bitree[2*E];
int n;
int flag=0;
int list[2*E];
int addedge(int u, int v)
{
    Edge[e].to = v;
    Edge[e].next = head[u];
    head[u] = e++;
    return 0;
}
int lowbit(int x)
{
    return x&(-x);
}
int Sum(int n)
{
    int sum = 0;
    while (n>0)
    {
        sum+=bitree[n];
        n = n - lowbit(n);
    }
    return sum;
}
void change(int i, int x) {
    while (i <= n) {
        bitree[i] = bitree[i] + x;
        i = i + lowbit(i);
    }
}
void dfs(int now,int fa)
{
    list[flag++]=now;
    for(int i=head[now];i!=-1;i=Edge[i].next)
    {
        if(Edge[i].to!=fa)
            dfs(Edge[i].to,now);
    }
    list[flag++]=now;
}
int main()
{
    int root;
    while(~scanf("%d%d",&n,&root))
    {
        if(n==0&&root==0)
            break;
        e=0;
        memset(head,-1,sizeof(head));
        for(int i=1;i<=n-1;i++)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            addedge(a, b);
            addedge(b, a);
        }
        flag=0;
        dfs(root,-1);
        int start[E],end[E],cnt[E],ans[E];
        n=2*n;
        memset(bitree,0,sizeof(bitree));
        memset(cnt,0,sizeof(cnt));
        for(int i=0;i<flag;i++)
        {

            if(cnt[list[i]]==0)
            {
                start[list[i]]=i;
                cnt[list[i]]++;
            }
            else
                end[list[i]]=i;
        }
        for(int i=1;i<=n;i++)
            change(i,1);
        for(int i=n/2;i>=1;i--)
        {
            ans[i]=(Sum(end[i]+1-1)-Sum(start[i]+1))/2;
            change(end[i]+1,-1);
            change(start[i]+1,-1);
        }
        for(int i=1;i<n/2;i++)
        {
            printf("%d ",ans[i]);
        }
        printf("%d\n",ans[n/2]);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值