UVA - 10562 Undraw the Trees

42 篇文章 0 订阅
Input
The first line of the input file (which you can assume comes from standard input) contains the number
of trees, T (1 ≤ T ≤ 20) drawn in the file. Then you would have T trees, each ending with a single
hash (‘#’) mark at the beginning of the line. All the trees drawn here are drawn vertically in top down
fashion. The labels of each of node can be any printable character except for the symbols ‘-’, ‘|’, ‘ ’
(space) and ‘#’. Every node that has children has a ‘|’ symbol drawn just below itself. And in the
next line there would be a series of ‘-’ marks at least as long as to cover all the immediate children.
The sample input section will hopefully clarify your doubts if there is any. No tree drawn here requires
more than 200 lines, and none of them has more than 200 characters in one line.


Output
Our trees are drawn with parenthesis and the node labels. Every subtree starts with an opening
parenthesis and ends with a closing parenthesis; inside the parenthesis the node labels are listed. The
sub trees are always listed from left to right. In our database each tree is written as a single string in
one line, and they do not contain any character except for the node labels and the parenthesis pair.
The node labels can be repeated if the original tree had such repetitions.


Sample Input


2
A
|
--------
B C D
| |
----- -
E F G
#
e
|
----
f g
#


Sample Output


(A(B()C(E()F())D(G())))

(e(f()g()))


分析:树的遍历,输入存放在二维数组中,然后用dfs遍历即可。


#include <iostream>
#include <cstring>
#include <cstdio>
#include <cctype>

using namespace std;
const int maxn = 210;
char tree[maxn][maxn];
int n;

void dfs(int row, int col) {
    printf("%c(", tree[row][col]);
    if(row<n-1 && tree[row+1][col]=='|') {
        int i = col;
        while(tree[row+2][i]=='-') i--;
        i++;
        while(tree[row+2][i]=='-' && tree[row+3][i]) {
			if(!isspace(tree[row+3][i])) dfs(row+3, i);
			i++;
		}
    }
    putchar(')');
}

void solve()
{
    n = 0;
    while(1) {
		fgets(tree[n], maxn, stdin);
		if(tree[n][0]=='#') break;
		n++;
    }

    putchar('(');
    if(n)
        for(int i=0; i<strlen(tree[0]); i++) {
            if(tree[0][i]!=' ') {dfs(0, i); break;}
        }
    printf(")\n");
}

int main()
{
    int T;
    fgets(tree[0], maxn, stdin);
    sscanf(tree[0], "%d",&T);
    while(T--) solve();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值