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;
}