看图写树Uva-10562

题意大概:

将多叉树转化为括号表达式。

每个节点除了“-”、“|”、和空格以外的其它字符表示。

每个非叶节点的正下方总会有一个“|”字符,然后下方是一排“-”字符,恰好覆盖所有的子节点的上方。

单独的一行“#”为数据结束标记。


代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=100;
char buf[maxn][maxn];
int num,cnt=0;
void action(int row,int col)
{
    if(buf[row+1][col]=='|'&&row+1<cnt)//如果有子节点
    {
        while(buf[row+2][col-1]=='-'&&(col-1)>=0)
            col--;//搜寻最左边的'-',然后记录!
        for(int i=col; buf[row+2][i]=='-'&&buf[row+3][i]!='\0'; i++)
        {
            if(buf[row+3][i]!=' ')
            {
                cout<<buf[row+3][i]<<"(";
                action(row+3,i);
            }
        }
    }
    cout<<")";//如果没有子节点就直接输出“)”
}
void fun()
{
    cout<<"(";
    if(cnt)
        for(int i=0; i<strlen(buf[0]); i++)
            if(buf[0][i]!=' ')
            {
                cout<<buf[0][i]<<"(";//找到根节点
                action(0,i);
                break;
            }
    cout<<")"<<endl;
}
int main()
{
    cin>>num;
    getchar();
    while(num--)
    {
        cnt=0;

        memset(buf,'\0',sizeof(buf));
        while(gets(buf[cnt])!=NULL)
        {
            cnt++;
            if(strcmp(buf[cnt-1],"#")==0)
                break;
        }
        fun();
    }
    return 0;
}
/*
2
      A
      |
-------------
B  C        D
   |        |
 -----      -
 E   F      G
#
(A(B()C(E()F())D(G())))
e
|
-----
f  g
#
(e(f()g()))

Process returned 0 (0x0)   execution time : 5.005 s
Press any key to continue.

*/


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值