-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6-12看图写树(图的DFS).cpp
59 lines (52 loc) · 1.21 KB
/
6-12看图写树(图的DFS).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
UVa 10562
*/
// 题意:把画得挺好看的多叉树转化为括号表示法
// 算法:直接在二维字符数组里递归。注意空树,并且结点标号可以是任意可打印字符
#include<cstdio>
#include<cctype>
#include<cstring>
using namespace std;
const int maxn = 200 + 10;
int n;
char buf[maxn][maxn];
// 递归遍历并且输出以字符buf[r][c]为根的树
void dfs(int r, int c) //r,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])) dfs(r + 3, i); // fgets读入的'\n'也满足isspace()
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_s(buf[0], "%d", &T);
while (T--) solve();
return 0;
}