例题6-17 看图写树(Undraw the Trees, UVa 10562)

原题链接:https://vjudge.net/problem/UVA-10562
分类:树
备注:多叉树的DFS

因为最外面那个括号让我搞了半天…看一眼紫书,原来最外层的括号和里面的括号规律不同,直接放在外面输出就好了…

代码如下:

#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
string line[205];
int depth;
void dfs(int L,int R,int pos) {
	for (int i = L; i < R && i < line[pos].length(); i++) {
		if (line[pos][i] != ' ' && line[pos][i] != '-' && line[pos][i] != '#') {
			printf("%c(", line[pos][i]);
			if (pos + 1 < depth && i < line[pos + 1].length() && line[pos + 1][i] == '|') {
				int l, r; l = r = i;
				while (l > 0 && line[pos + 2][l - 1] != ' ')l--;
				while (line[pos + 2][r] != ' ' && r < line[pos + 2].length())r++;
				dfs(l, r, pos + 3);
			}
			printf(")");
		}
	}
}
int main(void) {
	int T; 
	scanf("%d", &T);
	getchar();
	while (T--) { 
		depth = 0;
		while (getline(cin, line[depth++])) {
			if (line[depth - 1] == "#")break;
		}
		depth--;
		printf("(");
		if (depth)dfs(0, line[0].length(), 0);
		printf(")\n");
	}
	return 0;
}
发布了104 篇原创文章 · 获赞 97 · 访问量 4515

猜你喜欢

转载自blog.csdn.net/TK_wang_/article/details/105389563