diff --git a/2024/9/main-1.cpp b/2024/9/main-1.cpp new file mode 100644 index 0000000..5e321ad --- /dev/null +++ b/2024/9/main-1.cpp @@ -0,0 +1,53 @@ +#include +using namespace std; + +typedef unsigned long long ull; + +int main() { + ios::sync_with_stdio(0); + cin.tie(0); + + char c; + deque> blocks; + deque> frees; + int i = 0, n = 0; + bool rfree = false; + while (cin >> c) { + c -= '0'; + if (rfree) { + if (c > 0) { + frees.push_back({n, c}); + } + } else { + blocks.push_back({i++, n, c}); + } + rfree = !rfree; + n += c; + } + + while (frees.size() > 0) { + auto &[bi, bx, bn] = blocks.back(); + auto &[fx, fn] = frees[0]; + if (fx > bx) { + break; + } + int nmoved = min(fn, bn); + bn -= nmoved; + fn -= nmoved; + blocks.push_front({bi, fx, nmoved}); + if (fn == 0) { + frees.pop_front(); + } else { + fx += nmoved; + } + if (bn == 0) { + blocks.pop_back(); + } + } + + ull sum = 0; + for (auto &[bi, bx, bn] : blocks) { + sum += (ull)bi * (bn * bx + bn * (bn - 1) / 2); + } + cout << sum << '\n'; +} diff --git a/2024/9/main-2.cpp b/2024/9/main-2.cpp new file mode 100644 index 0000000..8a853eb --- /dev/null +++ b/2024/9/main-2.cpp @@ -0,0 +1,45 @@ +#include +using namespace std; + +typedef unsigned long long ull; + +int main() { + ios::sync_with_stdio(0); + cin.tie(0); + + char c; + vector> blocks; + vector> frees; + int i = 0, n = 0; + bool rfree = false; + while (cin >> c) { + c -= '0'; + if (rfree) { + if (c > 0) { + frees.push_back({n, c}); + } + } else { + blocks.push_back({i++, n, c, false}); + } + rfree = !rfree; + n += c; + } + + for (auto &[fx, fn] : frees) { + for (auto &[bi, bx, bn, bm] : blocks | views::reverse) { + if (bm || bn > fn || bx < fx) { + continue; + } + bx = fx; + bm = true; + fx += bn; + fn -= bn; + } + } + + ull sum = 0; + for (auto &[bi, bx, bn, bm] : blocks) { + sum += (ull)bi * (bn * bx + bn * (bn - 1) / 2); + } + cout << sum << '\n'; +}