码迷,mamicode.com
首页 > 其他好文 > 详细

看图写树Uva-10562

时间:2015-01-15 20:21:44      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:优化   dfs   多叉树   数据结构   

题意大概:

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

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

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

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


代码如下:

#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.

*/


看图写树Uva-10562

标签:优化   dfs   多叉树   数据结构   

原文地址:http://blog.csdn.net/u014004096/article/details/42745407

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!