【紫书】Undraw the Trees UVA - 10562 递归,字符串

时间:2024-09-04 20:07:02

题意:给你画了一颗树,你要把它的前序输出。

题解:读进到二维数组。边解析边输出。

坑:少打了个-1.

#define _CRT_SECURE_NO_WARNINGS
#include<cstring>
#include<cctype>
#include<cmath>
#include<cstdio>
#include<string>
#include<stack>
#include<list>
#include<set>
#include<map>
#include<queue>
#include<vector>
#include<sstream>
#include<iostream>
#include<algorithm> using namespace std;
const int maxn = + ;
char buf[maxn][maxn];
int n;
void dfs(int r, int c) {//打印以[r][c]为根的树
printf("%c(", buf[r][c]);
if (r + < n&&buf[r + ][c] == '|') {
int i = c;
while (i - >= && buf[r + ][i-] == '-')i--;
while (buf[r + ][i] == '-'&&buf[r + ][i] != '\0') {
if (!isspace(buf[r + ][i])) dfs(r + , i);//fgets 到的'\n'也能i是space掉。
i++;
} }
cout << ')';
}
void solve() {
n = ;
for (;;) {
fgets(buf[n], maxn, stdin);
if (buf[n][] == '#')break; else n++;
}
printf("(");
if (n) {
for (int i = ; i < strlen(buf[]); i++) {
if (buf[][i] != ' ') { dfs(, i); break; }
}
}
cout << ')' << endl;
}
int main() {
int t; fgets(buf[], maxn, stdin);
sscanf(buf[], "%d", &t);
while (t--) {
solve();
}
system("pause");
return ;
}
/*
2
A
|
--------
B C D
| |
----- -
E F G
#
e
|
----
f g
# (A(B()C(E()F())D(G())))
(e(f()g()))*/