fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Adjacency list for the filesystem
  5. map<string, vector<string>> children;
  6.  
  7. // Counters for directories and files
  8. int dir_count = 0, file_count = 0;
  9.  
  10. // Recursive function to print the tree
  11. // node: current node name
  12. // depth: depth in the tree (root = 0)
  13. // last_branch: for each ancestor level, true if that ancestor was the last child
  14. void print_tree(const string& node, int depth, vector<bool>& last_branch) {
  15. if (depth == 0) {
  16. // Print the root directory
  17. cout << node << "\n";
  18. dir_count++;
  19. } else {
  20. // Print indentation for each ancestor level
  21. for (int i = 0; i < depth - 1; i++) {
  22. if (last_branch[i]) {
  23. // no more siblings at this level
  24. cout << " ";
  25. } else {
  26. // still have siblings → draw vertical bar
  27. cout << "| ";
  28. }
  29. }
  30. // Print the branch symbol for this node
  31. bool is_last = last_branch[depth - 1];
  32. cout << (is_last ? "|__ " : "|-- ");
  33. cout << node << "\n";
  34.  
  35. // Count directory or file
  36. if (!children.count(node)) {
  37. file_count++;
  38. return;
  39. } else {
  40. dir_count++;
  41. }
  42. }
  43.  
  44. // Recurse into children (already sorted)
  45. auto &vec = children[node];
  46. for (size_t i = 0; i < vec.size(); i++) {
  47. last_branch.push_back(i + 1 == vec.size());
  48. print_tree(vec[i], depth + 1, last_branch);
  49. last_branch.pop_back();
  50. }
  51. }
  52.  
  53. int main() {
  54. ios::sync_with_stdio(false);
  55. cin.tie(nullptr);
  56.  
  57. string root;
  58. int N;
  59. cin >> root >> N;
  60.  
  61. // Read filesystem
  62. for (int i = 0; i < N; i++) {
  63. string parent, child;
  64. cin >> parent >> child;
  65. children[parent].push_back(child);
  66. // leave child out of map if it's a file (no children)
  67. }
  68.  
  69. // Sort each directory's contents
  70. for (auto &p : children) {
  71. sort(p.second.begin(), p.second.end());
  72. }
  73.  
  74. // Print tree
  75. vector<bool> last_branch;
  76. print_tree(root, 0, last_branch);
  77.  
  78. // Blank line then counts
  79. cout << "\n"
  80. << dir_count << " directories, "
  81. << file_count << " files\n";
  82.  
  83. return 0;
  84. }
  85.  
Success #stdin #stdout 0.01s 5284KB
stdin
home
9
home hacker42
hacker42 downloads
hacker42 desktop
hacker42 labs
downloads movie.mp4
downloads book.pdf
labs 1337
1337 libstd.c
1337 printf.c
stdout
home
|__ hacker42
    |-- desktop
    |-- downloads
    |   |-- book.pdf
    |   |__ movie.mp4
    |__ labs
        |__ 1337
            |-- libstd.c
            |__ printf.c

5 directories, 5 files