poj 3437

来源:互联网 发布:建筑长宽数据 编辑:程序博客网 时间:2024/06/06 01:14

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

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


 

原创粉丝点击