zoj 3805 Machine

本文解决ZOJ3805题目的树宽度计算问题,介绍了一种模仿BFS思想的方法,通过递归地计算左子树和右子树的最大值来确定整棵树的宽度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接: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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值