hdu 3887 Counting Offspring(dfs序+树状数组)

来源:互联网 发布:咸鱼质量问题淘宝介入 编辑:程序博客网 时间:2024/05/20 13:14

Counting Offspring

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


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<n<=10^5) and p, representing this tree has n nodes, its root is p.
Following n-1 lines, each line has two integers, representing an edge in this tree.
The input terminates with two zeros.
 

Output
For each test case, output n integer in one line representing f(1), f(2) … f(n), separated by a space.
 

Sample Input
15 77 107 17 97 37 410 1414 214 139 119 66 56 83 153 120 0
 

Sample Output
0 0 0 0 0 1 6 0 3 1 0 0 0 2 0
 

Author
bnugong
 


#include<cstdio>#include<cstring>#include<cmath>#include<iostream>#include<algorithm>#include<map>#include<vector>#include<queue>#include<stack>#define eps 1e-8const int inf = 0x3f3f3f3f;const long long mod=1e9+7;const int N=100020;using namespace std;int n,p,cnt,k;struct node{    int v,nxt;}s[N*2];int first[N];int in[N],out[N];int ans[N];int ar[N];int lowbit(int x){    return x&-x;}void add(int i,int w){    while(i<=n)    {        ar[i]+=w;        i+=lowbit(i);    }}int sum(int k){    int ans=0;    while(k)    {        ans+=ar[k];        k-=lowbit(k);    }    return ans;}int dfs(int u,int pre){        in[u]=++cnt;    for(int i=first[u];i;i=s[i].nxt)    {        int v=s[i].v;        if(v==pre)            continue;        dfs(v,u);    }    out[u]=cnt;}int main(){    int u,c;    while(~scanf("%d%d",&n,&p)&&(n+p))    {        memset(first,0,sizeof(first));        memset(ar,0,sizeof(ar));        k=1,cnt=0;        for(int i=1;i<n;i++)        {           scanf("%d%d",&u,&c);        s[k].v = c;        s[k].nxt = first[u];        first[u] = k++;        s[k].v=u;        s[k].nxt=first[c];        first[c]=k++;        }        dfs(p,-1);       for(int i=1;i<=n;i++)       {           int rr=sum(out[i])-sum(in[i]-1);           printf("%d%c",rr,((i==n)?'\n':' '));           add(in[i],1);       }    }}




阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 咳嗽能吃橙子吗 咳嗽看什么科室 小儿风寒咳嗽 小孩子咳嗽怎么办 不停咳嗽怎么办 咳嗽震的头疼 咳嗽头疼是怎么回事 咳嗽雾化用什么药 小孩咳嗽厉害怎么办 风寒咳嗽吃什么药 孕期咳嗽怎么办 咳嗽的图片卡通图 风热咳嗽和风寒咳嗽的区别 儿童咳嗽食疗 咳嗽喝什么茶 咳嗽的英文单词 喉咙干痒咳嗽怎么办 咳嗽呼吸困难 新生儿咳嗽怎么回事 咳嗽咳得胸口疼 咳嗽看什么科 咳嗽吃什么好 到晚上就咳嗽怎么回事 咳嗽胸口疼是怎么回事 怎样快速止咳嗽 咳嗽有浓痰是怎么回事 咳嗽有血是什么原因 咳嗽吐黄痰是怎么回事 气短咳嗽是怎么回事 睡到半夜咳嗽怎么回事 咳嗽背痛是什么原因 气喘咳嗽是什么原因 咳嗽气喘是什么原因 支气管咳嗽症状 肺热咳嗽症状 咳嗽带血是什么原因 咳嗽胸口疼怎么回事 咳嗽喉咙哑了怎么办 宝宝咳嗽吐奶怎么回事 咳嗽了吃什么好的快 孩子老咳嗽怎么回事