Uva10562——Undraw the Trees

上来一看感觉难以下手,仔细想想就是dfs啊!!!!

 1 #include <cstdio>
 2 #include<iostream>
 3 #include<iomanip>
 4 #include<cstring>
 5 #include<string>
 6 #include<queue>
 7 #include<algorithm>
 8 using namespace std;
 9 int n=0;
10 char s[210][210];
11 void dfs (int x,int y)
12 {//x为第几行,y为某一行的第几个
13    cout<<s[x][y]<<'(';
14    if(x+1<n&&s[x+1][y]=='|')//如果有子树,就向下搜
15    {
16        int kk=y;
17        while(kk-1>=0&&s[x+2][kk-1]=='-')kk--;//找到最左边
18        while(s[x+2][kk]=='-'&&s[x+3][kk]!='')
19        {
20            if(!isspace(s[x+3][kk]))
21        {
22            dfs(x+3,kk);//从父亲到儿子差3行
23        }
24        kk++;
25        }
26 
27    }
28    cout<<')';
29 }
30 int main()
31 {
32     int t;
33     cin>>t;
34     getchar();
35     while(t--)
36     {
37         n=0;
38         memset(s,0,sizeof(s));
39         while(1)
40         {
41             gets(s[n]);
42             if(s[n][0]=='#'){break;}
43             n++;
44         }
45         int l;
46         for(l=0;l<strlen(s[0]);l++){if(!isspace(s[0][l]))break;}//找到根节点
47         cout<<'(';
48         dfs(0,l);
49         cout<<')';
50         cout<<endl;
51 
52     }
53     return 0;
54 }

还是属于水题一类的吧!

原文地址:https://www.cnblogs.com/kayiko/p/10712923.html