From 158c2e5dffe0e7ae24e9d93addb74b4bba12531b Mon Sep 17 00:00:00 2001 From: dzwdz Date: Wed, 7 Dec 2022 11:20:41 +0100 Subject: day 7 part 1 partially coded on my phone --- 22.7/main.cpp | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 22.7/main.cpp (limited to '22.7') 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 +#include +#include +#include +using namespace std; + +class +Directory +{ +public: + Directory *parent = nullptr; + unordered_map 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 +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; +} -- cgit 1.4.1-2-gfad0