#include #include #include #include #include #include #include namespace qi = boost::spirit::qi; namespace { auto suffixed(std::uint64_t x, std::uint64_t y) -> std::optional { while (x > 0) { if (y == 0) { return x; } if (x % 10 != y % 10) return std::nullopt; x /= 10; y /= 10; } return std::nullopt; } auto check(bool const part2, std::uint64_t const target, std::vector const& numbers) -> bool { if (numbers.size() == 0) { return false; } auto work = std::stack>{}; work.emplace(numbers.size() - 1, target); while (not work.empty()) { auto const [i, t] = work.top(); work.pop(); auto const x = numbers[i]; if (i == 0) { if (x == t) { return true; } } else { if (x < t) { work.emplace(i - 1, t - x); } if (t % x == 0) { work.emplace(i - 1, t / x); } if (part2) { if (auto const u = suffixed(t, x)) { work.emplace(i - 1, *u); } } } } return false; } } // namespace auto Main(std::istream & in, std::ostream & out) -> void { auto const input = aocpp::ParseSimple >>> (in, *(qi::ulong_long >> ':' >> *(' ' >> qi::ulong_long) >> '\n')); std::uint64_t p1{}, p2{}; for (auto && [x, xs] : input) { if (check(false, x, xs)) p1 += x; if (check(true, x, xs)) p2 += x; } out << "Part 1: " << p1 << "\n" << "Part 2: " << p2 << "\n"; }