poj 3437

参考了别人的代码,写的第一棵树.主要思路是先构建一个树然后求其高度.

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 11000;
struct tnode{
   int par; //父亲
   int lc;  //左儿子
   int rc;  //右二子
   int ltc;  //最后一个儿子
}tr[maxn];//构建树节点

int Cal_Height(int n){ //计算转换之后树的高度
    int LH = 0, RH = 0;
    if(tr[n].lc != -1) LH = Cal_Height( tr[n].lc);
    if(tr[n].rc != -1) RH = Cal_Height( tr[n].rc);
    return (( LH > RH ? LH : RH ) + 1);
}

int main(){
    char s[maxn << 1];
    int cnt = 0;
    while(scanf("%s",s)){
          if(s[0] == '#') break;
          memset(tr, -1, sizeof(tr));
          int cur,nod,h1,mh1;
          cur = nod = h1 = mh1 = 0;
          for(int i = 0 ; s[i] != '\0'; ++i){
              if(s[i] == 'd'){
                   h1++;
                   mh1 = max( h1, mh1);
                   nod++;
                   tr[nod].par = cur;
                   if(tr[cur].lc == -1){ //如果它的左儿子为空,说明这是第一个儿子,所以放在做儿子里
                       tr[cur].lc = nod;
                       tr[cur].ltc = nod;
                   }
                   else{                //否则放在最后一个儿子的右儿子里面
                       tr[tr[cur].ltc].rc = nod;
                       tr[cur].ltc = nod;
                   }
                   cur = nod;
              }
              else{
                  h1--;
                  cur = tr[cur].par;    //回溯到父亲
              }
          }
           printf("Tree %d: %d => %d\n",++cnt,mh1,Cal_Height(0)-1);
    }

   return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值