advent-of-code/2024/9/main-2.cpp

46 lines
780 B
C++
Raw Normal View History

2024-12-08 22:53:26 -08:00
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
char c;
vector<tuple<int, int, int, bool>> blocks;
vector<tuple<int, int>> 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';
}