题目链接:zoj 3805
题意:
思路:就是树的宽度等于左子树和右子树的最大值,若相等等于子树值+1,第一次做树上的题,不会从叶子往根递推,于是就模仿BFS的思想把节点按照深度大小存起来了,写了好长时间,没时间做别的题了...
cpp:http://paste.ubuntu.com/8130830/
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
#define maxn 10010
struct Node {
int wight,son[3];
void insert(int x){
if(son[0]==-1){
son[0]=x;
}
else{
son[1]=x;
}
}
void init(){
wight=1;
son[0]=-1;
son[1]=-1;
son[2]=-1;
}
}node[maxn];
int layer[maxn];
int n, tp;
void be_layer(){
int tot=0,cnt=1;
layer[1]=1;
while (1){
++tot;
for(int i=0;node[layer[tot]].son[i]!=-1;i++)
{
layer[++cnt]=node[layer[tot]].son[i];
}
if(cnt>=n)
{
break;
}
}
}
void prepare(){
for(int i=1;i<=n;i++){
node[i].init();
}
for(int i=2;i<=n;i++)
{
scanf("%d",&tp);
node[tp].insert(i);
}
}
void slove(){
for(int i=n;i>=1;i--)
{
int dad=layer[i];
int lson=node[dad].son[0];
int rson=node[dad].son[1];
if(lson==-1){
continue;
}
else if(rson==-1) {
node[dad].wight=node[lson].wight;
}
else if(node[dad].son[2]==-1){
if(node[lson].wight>node[rson].wight)
{
node[dad].wight=node[lson].wight;
}
else if(node[lson].wight<node[rson].wight)
{
node[dad].wight=node[rson].wight;
}
else if(node[lson].wight==node[rson].wight){
node[dad].wight=node[lson].wight+1;
}
}
}
}
int main ()
{
freopen("data.in","r",stdin);
while (~scanf("%d",&n)){
prepare();
be_layer();
slove();
printf("%d\n",node[1].wight);
}
return 0;
}