http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1503
题意:将一棵树形式转化后输出,看样例即可理解。
题解:采用递归,对每个节点,输出其后再递归处理它所包含的子节点。通过“------”列来确定其子节点所在的范围。注意节点不一定为字母且可能存在空树。
#include <cstdio>
#include <cstring>
#include <cmath>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
const double eps=1e-7;
const double INF=1e50;
const double pi=acos(-1);
#define N 15
char s[1000][300];
int n;
void print(int m,int w)
{
printf("%c(",s[m][w]);
if ((m+3>n) || s[m+1][w]!='|')//需要加上s[m+1][w]!='|',因为叶子节点不一定在树的最底端
{
printf(")");
return ;
}
int p,q,l;
l=strlen(s[m+2])-1;
p=q=w;
while (s[m+2][p-1]=='-' && p>0) p--;
while (s[m+2][q+1]=='-' && q<l) q++;
for (int i=p;i<=q && i<(int)strlen(s[m+3]);i++)
if (s[m+3][i]!= '-' && s[m+3][i]!='|' && s[m+3][i]!=' ' && s[m+3][i]!='#')
print(m+3,i);
printf(")");
}
int main()
{
freopen("a","r",stdin);
int T,i;
scanf("%d",&T);
gets(s[0]);
for (int kk=1;kk<=T;kk++)
{
n=0;
while (strcmp(s[n],"#")!=0)
{
n++;
gets(s[n]);
}
n--;
printf("(");
for (i=0;i<(int)strlen(s[1]);i++)
if (s[1][i]!= '-' && s[1][i]!='|' && s[1][i]!=' ' && s[1][i]!='#')
print(1,i);
printf(")");
printf("\n");
}
return 0;
}