看图写树 (Undraw the Trees UVA

题目描述:

原题:https://vjudge.net/problem/UVA-10562

题目思路:

递归找结点

//自己的代码测试过了,一直WA,贴上紫书的代码

AC代码

#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) {
  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] != '') {
      if(!isspace(buf[r+3][i])) dfs(r+3, i); // fgets读入的'
'也满足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(")
");
}

int main() {
  int T;
  fgets(buf[0], maxn, stdin);
  sscanf(buf[0], "%d", &T);
  while(T--) solve();
  return 0;
}
原文地址:https://www.cnblogs.com/secoding/p/9539529.html