【紫书】Undraw the Trees UVA - 10562 递归,字符串
题意:给你画了一颗树,你要把它的前序输出。
题解:读进到二维数组。边解析边输出。
坑:少打了个-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 = 200 + 5; char buf[maxn][maxn]; int n; 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'也能i是space掉。 i++; } } cout << ')'; } 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; } } } cout << ')' << endl; } int main() { int t; fgets(buf[0], maxn, stdin); sscanf(buf[0], "%d", &t); while (t--) { solve(); } system("pause"); return 0; } /* 2 A | -------- B C D | | ----- - E F G # e | ---- f g # (A(B()C(E()F())D(G()))) (e(f()g()))*/
成功的路并不拥挤,因为大部分人都在颓(笑)
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步