UVA - 10562 Undraw the Trees

来源:互联网 发布:php cookie存储目录 编辑:程序博客网 时间:2024/06/05 05:55
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;}


0 0
原创粉丝点击