You observed amoebae and kept some records. Initially, there was one amoeba, numbered $1$. You made $N$ records. According to the $i$-th record, the amoeba numbered $A_i$ disappeared by dividing itself into two new amoebae, which were then numbered $2i$ and $2i+1$. For each $k=1,\ldots,2N+1$, how many generations away is amoeba $k$ from amoeba $1$?Problem Statement
Here, amoeba $A_i$ is said to be the parent of amoebae $2i$ and $2i+1$.Constraints
Input
The input is given from Standard Input in the following format:
$N$ $A_1$ $A_2$ $\ldots$ $A_N$
Output
Print $2N+1$ lines. The $k$-th line should contain the generation distance between amoeba $1$ and amoeba $k$.
Sample Input 1
2 1 2
Sample Output 1
0 1 1 2 2
From amoeba $1$, amoebae $2$ and $3$ were born. From amoeba $2$, amoebae $4$ and $5$ were born.
- Amoeba $1$ is zero generations away from amoeba $1$.
- Amoeba $2$ is one generation away from amoeba $1$.
- Amoeba $3$ is one generation away from amoeba $1$.
- Amoeba $4$ is one generation away from amoeba $2$, and two generations away from amoeba $1$.
- Amoeba $5$ is one generation away from amoeba $2$, and two generations away from amoeba $1$.
Sample Input 2
4 1 3 5 2
Sample Output 2
0 1 1 2 2 3 3 2 2
按照题意建树,计算深度。
#include<cstdio>
const int N=4e5+5;
int a[N],n,lc[N],rc[N],dep[N];
void dfs(int x)
{
if(lc[x])
{
dep[lc[x]]=dep[x]+1;
dfs(lc[x]);
}
if(rc[x])
{
dep[rc[x]]=dep[x]+1;
dfs(rc[x]);
}
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",a+i);
for(int i=1;i<=n;i++)
lc[a[i]]=2*i,rc[a[i]]=2*i+1;
dfs(1);
for(int i=1;i<=2*n+1;i++)
printf("%d\n",dep[i]);
return 0;
}
标签:Amoeba,generation,Ameba,away,dep,amoeba,2i
From: https://www.cnblogs.com/mekoszc/p/16906439.html