看图写树 Undraw the Trees UVA10562

题目描述

 输入格式

输出格式

【输入样例】

2
A
|
--------
BC D
| |
----- -
E FG
#
e
|
----
f g
#

【输出样例】 

(A(B()C(E()F())D(G())))
(e(f()g()))
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cctype>
using namespace std;
const int maxn = 200 + 10;
int n;
char buf[maxn][maxn];
//递归遍历并且输出以字符buf[r][c]为根的树
void dfs(int r, int c)
{
    printf("%c(", buf[r][c]);
    if (r + 1 < n && buf[r + 1][c] == '|') //有子树
    {
        int i = c;
        while (i - 1 >= 0 && buf[r + 2][i - 1] == '-') // 找“----”的左边界
            i--;
        while (buf[r + 2][i] == '-' && buf[r + 3][i] != '\0')
        {
            if (!isspace(buf[r + 3][i])) //fgets读入的“\n”也满足isspace();
                dfs(r + 3, i);
            i++;
        }
    }
    printf(")");
}
void solve()
{
    n = 0;
    for (;;)
    {
        fgets(buf[n], maxn, stdin);
        if (buf[n][0] == '#')
            break;
        else
            n++;
    }
    printf("(");
    if (n)
    {
        for (int i = 0; i < strlen(buf[0]); i++)
            if (buf[0][i] != ' ')
            {
                dfs(0, i);
                break;
            }
    }
    printf(")\n");
}
int main()
{
    int T;
    fgets(buf[0], maxn, stdin);
    sscanf(buf[0], "%d", &T);
    while (T--)
        solve();
    return 0;
}

 

posted @ 2020-07-27 14:04  我等着你  阅读(156)  评论(0)    收藏  举报