diff options
author | dzwdz | 2022-12-07 11:20:41 +0100 |
---|---|---|
committer | dzwdz | 2022-12-07 11:20:41 +0100 |
commit | 158c2e5dffe0e7ae24e9d93addb74b4bba12531b (patch) | |
tree | 8ba6e689bab37ec977f206e7143ff93d8e299224 | |
parent | d128bfa35f52916e190c2515249be721b68a8db0 (diff) |
day 7 part 1
partially coded on my phone
-rw-r--r-- | 22.7/main.cpp | 83 |
1 files changed, 83 insertions, 0 deletions
diff --git a/22.7/main.cpp b/22.7/main.cpp new file mode 100644 index 0000000..66c85e8 --- /dev/null +++ b/22.7/main.cpp @@ -0,0 +1,83 @@ +#include <iostream> +#include <string> +#include <unordered_map> +#include <vector> +using namespace std; + +class +Directory +{ +public: + Directory *parent = nullptr; + unordered_map<string, Directory*> dirs; + long direct_size = 0; + + void + mkdir(string name) + { + dirs[name] = new Directory(); + dirs[name]->parent = this; + } + + void + mkfile(string name, long size) + { + (void) name; + direct_size += size; + } + + Directory* + cd(string path) + { + return parent; + } +}; + +template<typename F> +long +getSizes(Directory *dir, F&& fn) +{ + long size = dir->direct_size; + for (auto &c : dir->dirs) { + size += getSizes(c.second, fn); + } + fn(size); + return size; +} + +int +main() +{ + Directory root; + Directory *pwd = &root; + for (string line; getline(cin, line); ) { + if (line.compare(0, 4, "$ cd") == 0) { + string path = line.substr(5); + if (path == "/") { + pwd = &root; + } else if (path == "..") { + pwd = pwd->parent; + } else { + pwd = pwd->dirs[path]; + } + if (pwd == nullptr) throw "bad input"; + } + if (line[0] != '$') { + int pos = line.find(" "); + string meta = line.substr(0, pos); + string name = line.substr(pos + 1); + if (meta == "dir") { + pwd->mkdir(name); + } else { + pwd->mkfile(name, stol(meta)); + } + } + } + + long total1 = 0; + getSizes(&root, [&](long size){ + if (size <= 100000) + total1 += size; + }); + cout << total1 << endl; +} |