题意:将多叉树转化为括号表示法。
分析:gets读取,dfs就好了。注意,样例中一行的最后一个字母后是没有空格的。
#pragma comment(linker, "/STACK:102400000, 102400000") #include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<stack> #include<deque> #include<queue> #include<list> #define Min(a, b) ((a < b) ? a : b) #define Max(a, b) ((a < b) ? b : a) typedef long long ll; typedef unsigned long long llu; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const ll LL_INF = 0x3f3f3f3f3f3f3f3f; const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const int MOD = 1e9 + 7; const double pi = acos(-1.0); const double eps = 1e-8; const int MAXN = 200 + 10; const int MAXT = 10000 + 10; using namespace std; char s[MAXN][MAXN]; int cnt; void dfs(int x, int y){ printf("%c(", s[x][y]); if(x == cnt){ return; } if(s[x + 1][y] == '|'){//有子树 int st = y; int et = y; while(s[x + 2][st - 1] == '-' && st - 1 >= 0) --st;//找左边界,且要保证下标不为负数 while(s[x + 2][et] == '-') ++et;//找右边界 for(int j = st; j < et && s[x + 3][j] != '\0'; ++j){//横线的右边界下不一定有结点,所以s[x + 3][j] != '\0' if(!isspace(s[x + 3][j])){ dfs(x + 3, j); printf(")"); } } } } int main(){ //freopen("in.txt", "r", stdin); int T; scanf("%d", &T); getchar(); while(T--){ memset(s, 0, sizeof s); cnt = 0; while(gets(s[cnt])){//gets读入 if(s[cnt][0] == '#') break; ++cnt; } printf("("); int len = strlen(s[0]); for(int j = 0; j < len; ++j){ if(cnt == 0) break;//空树 if(!isspace(s[0][j])){//是结点 dfs(0, j); printf(")"); } } printf(")\n"); } return 0; }