Advertisement
Guest User

Untitled

a guest
May 20th, 2019
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using tree_t = std::vector<std::string>;
  6.  
  7. struct pt {
  8. size_t x, y;
  9. };
  10.  
  11. bool valid(const tree_t& tree, const pt p) {
  12. if (p.y >= tree.size()) return false;
  13. if (p.x >= tree[p.y].size()) return false;
  14. return true;
  15. }
  16.  
  17. pt go_left(const pt p, size_t i) { return {p.x - i, p.y + i}; }
  18. pt go_right(const pt p, size_t i) { return {p.x + i, p.y + i}; }
  19. char at(const tree_t& tree, const pt p) { return tree[p.y][p.x]; }
  20.  
  21. bool has_left_child(const tree_t& tree, const pt p) {
  22. return valid(tree, go_left(p, 1)) && at(tree, go_left(p, 1)) == '/' &&
  23. valid(tree, go_left(p, 2));
  24. }
  25.  
  26. bool has_right_child(const tree_t& tree, const pt p) {
  27. return valid(tree, go_right(p, 1)) && at(tree, go_right(p, 1)) == '\\' &&
  28. valid(tree, go_right(p, 2));
  29. }
  30.  
  31. pt root(const tree_t& tree) {
  32. size_t root = -1;
  33. for (size_t i = 0; i < tree.front().size(); i++) {
  34. if (tree.front()[i] != ' ') {
  35. root = i;
  36. }
  37. }
  38. return {root, 0};
  39. }
  40.  
  41. void dfs(const tree_t& tree, pt p, std::string& my_stack,
  42. std::string& solution) {
  43. bool has_child = false;
  44. my_stack += at(tree, p);
  45. if (has_left_child(tree, p)) {
  46. has_child = true;
  47. dfs(tree, go_left(p, 2), my_stack, solution);
  48. }
  49. if (has_right_child(tree, p)) {
  50. has_child = true;
  51. dfs(tree, go_right(p, 2), my_stack, solution);
  52. }
  53. if (!has_child) {
  54. if (solution.back() == ']') {
  55. solution += ", ";
  56. }
  57. solution += "[";
  58.  
  59. for (char c : my_stack) {
  60. solution += c;
  61. solution += ", ";
  62. }
  63. solution.pop_back();
  64. solution.back() = ']';
  65. }
  66. my_stack.pop_back();
  67. }
  68.  
  69. std::string solution(const tree_t& tree) {
  70. pt r = root(tree);
  71. std::string my_stack = "";
  72. std::string solution = "[";
  73. dfs(tree, r, my_stack, solution);
  74. solution += "]";
  75. return solution;
  76. }
  77.  
  78. int main() {
  79. // clang-format off
  80. const tree_t tree = {
  81. " 1",
  82. " / \\",
  83. " 2 3",
  84. " / \\",
  85. " 4 5"
  86. };
  87. // clang-format on
  88. std::cout << solution(tree) << std::endl;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement