• UVa 10562看图写树(二叉树遍历)


    https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1503

    这道题错了好多次,一开始我直接是cin>>t,但前面可能还有空格,所以不对。就按照书上的用了fgets(buf[0],maxn,stdin)。

    题目的本质就是二叉树的遍历问题,直接运用dfs遍历即可。

     1 #include<iostream>
     2 #include<cstring>
     3 #include<cctype>
     4 using namespace std;
     5 
     6 const int maxn = 220;
     7 char buf[maxn][maxn];
     8 int n;
     9 
    10 void dfs(int r, int i)
    11 {
    12     cout << buf[r][i];
    13     cout << "(";
    14     if (r + 1<n && buf[r + 1][i] == '|')
    15     {
    16         int k = i;
    17         while (k - 1 >= 0 && buf[r + 2][k - 1] == '-')  k--;
    18         while (buf[r + 2][k] == '-' && buf[r+3][k]!='')
    19         {
    20             if (!isspace(buf[r + 3][k])) dfs(r + 3, k);
    21             k++;
    22         }
    23     }
    24     cout << ")";
    25 }
    26 void solve()
    27 {
    28     n = 0;
    29     for (;;)
    30     {
    31         fgets(buf[n], maxn, stdin);
    32         if (buf[n][0] == '#') break;
    33         else n++;
    34     }
    35     cout << "(";
    36     if (n)
    37     {    
    38         int l = strlen(buf[0]);
    39         for (int i = 0; i < l; i++)
    40             if (buf[0][i] != ' ')    { dfs(0, i); break; }
    41     }
    42     cout << ")"<<endl;
    43 }
    44 
    45 int main()
    46 {
    47     int t;
    48     fgets(buf[0], maxn, stdin);
    49     sscanf(buf[0], "%d", &t);
    50     while (t--)  solve();
    51     return 0;
    52 }
  • 相关阅读:
    百斯特
    C++
    转载
    转载+整理
    转载
    转载
    转载
    C++
    转载
    CodeForces
  • 原文地址:https://www.cnblogs.com/zyb993963526/p/6178952.html
Copyright © 2020-2023  润新知