diff options
author | kaiwu <kaiwu2004@gmail.com> | 2022-05-12 10:05:40 +0800 |
---|---|---|
committer | kaiwu <kaiwu2004@gmail.com> | 2022-05-12 10:05:40 +0800 |
commit | ce1776fa51e0cb9f20abb164da64fb42d4520691 (patch) | |
tree | aa426daecdb12e0375d36bc27d001f717b3db8c3 /src/2018/day8/aoc.cpp | |
parent | 6a51123201c23693f87b6b69b9db73aed39af874 (diff) | |
download | advent-of-code-ce1776fa51e0cb9f20abb164da64fb42d4520691.tar.gz advent-of-code-ce1776fa51e0cb9f20abb164da64fb42d4520691.zip |
2018 day8 part1
Diffstat (limited to 'src/2018/day8/aoc.cpp')
-rw-r--r-- | src/2018/day8/aoc.cpp | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/src/2018/day8/aoc.cpp b/src/2018/day8/aoc.cpp index 585f144..2f7729f 100644 --- a/src/2018/day8/aoc.cpp +++ b/src/2018/day8/aoc.cpp @@ -1,5 +1,58 @@ #include "aoc.h" +#include <stack> +#include <vector> namespace aoc2018 { +static void get_number(const char** pp, int* d) { + const char* p = *pp; + *d = 0; + while (*p >= '0' && *p <= '9') { + *d = *d * 10 + *p - '0'; + p++; + } + *pp = p; } + +struct header { + int nodes; + int metas; +}; + +int day8(line_view file) { + std::vector<int> is; + const char* p1 = file.line; + const char* p2 = file.line + file.length; + while (p1 < p2) { + if (*p1 >= '0' && *p1 <= '9') { + int d{0}; + get_number(&p1, &d); + is.push_back(d); + } + p1++; + } + + std::stack<header> hs; + size_t index{0}; + int total{0}; + hs.push({is[index], is[index + 1]}); + index += 2; + while (!hs.empty()) { + auto& h = hs.top(); + if (h.nodes > 0) { + hs.push({is[index], is[index + 1]}); + index += 2; + h.nodes -= 1; + } else { + while (h.metas > 0) { + total += is[index]; + index += 1; + h.metas -= 1; + } + hs.pop(); + } + } + return total; +} + +} // namespace aoc2018 |