diff --git a/day 9/day_9_max_n.cpp b/day 9/day_9_max_n.cpp new file mode 100644 index 0000000000000000000000000000000000000000..246b83b8d158143ef734daab4fae4711eeb0dd82 --- /dev/null +++ b/day 9/day_9_max_n.cpp @@ -0,0 +1,154 @@ +#include <bits/stdc++.h> + +#ifdef LOCAL +#include "./cpp-dump/cpp-dump.hpp" +#define pr(x) cpp_dump(x) +#endif + +using namespace std; + +#define Mod(x,y) (((x)%(y)+(y))%(y)) +#define rep(i, a, b) for(ll (i) = (a); (i) < (b); ++(i)) +#define all(x) begin(x), end(x) +#define pb push_back +#define gcd __gcd +#define sz(x) (ll)(x.size()) + +typedef long long ll; +typedef unsigned long long ull; +typedef pair<ll, ll> pii; +typedef vector<ll> vi; +typedef vector<pii> vii; + +const bool debug = false; + +ll ans = 0; + +vector<vi> v; + +bool fill(int i, ll y) { + rep(j, 0, sz(v[i])) { + if (v[i][j] == -1) { + v[i][j] = y; + break; + } + } + rep(j, 0, sz(v[i])) if (v[i][j] == -1) return true; + return false; +} + +ll empty_left(int i) { + int ret = 0; + rep(j, 0, sz(v[i])) if (v[i][j] == -1) ret++; + return ret; +} +ll numbers_left(int i) { + int ret = 0; + rep(j, 0, sz(v[i])) if (v[i][j] != -1) ret++; + return ret; +} + +bool is_complete_file(int i) { + return empty_left(i) == 0 && numbers_left(i) > 0; +} +void fill_with_numbers(int i, vi w) { + int j = 0; + rep(k, 0, sz(v[i])) if (v[i][k] == -1) { + v[i][k] = w[j]; + j++; + if (j >= sz(w)) break; + } +} + + +void solve() { + string s; + cin >> s; + if (sz(s)%2 == 1) s += "0"; + stringstream ss; + ss << s; + + char c1, c2; + ll x, y; + ll id = 0; + while(ss >> c1 >> c2) { + x = c1-'0'; + y = c2-'0'; + vi w1, w2; + rep(i, 0, x) { + w1.pb(id); + } + rep(j, 0, y) w2.pb(-1); + + v.pb(w1); + v.pb(w2); + + id++; + } + + ll lst = sz(v)-1; + + if (sz(v[lst]) == 0) { + lst--; + v.pop_back(); + } + + bool PART1 = true; + if (PART1) rep(i, 0, v.size()) if (i%2 == 1) { + if (!fill(i, -1)) continue; + + while(fill(i, -1)) { + if (i >= lst) break; + + while(sz(v[lst])) { + ll y = v[lst].back(); + v[lst].pop_back(); + + if (!fill(i, y)) break; + } + + if (sz(v[lst]) == 0) { + lst-=2; + } + } + } + + if (!PART1) for (int j = sz(v)-1; j >= 0; j--) { + if (is_complete_file(j)) { + ll file_sz = numbers_left(j); + + for (int i = 0; i < j; i++) { + if (empty_left(i) >= file_sz) { + fill_with_numbers(i, v[j]); + + rep(k, 0, sz(v[j])) v[j][k] = -1; + break; + } + } + } + } + + + id = 0; + for (auto vv : v) { + for (ll x : vv) { + if (x >= 0) ans += id*x; + id++; + } + } + + if (PART1) pr("Part 1"); else pr("Part 2"); + pr(ans); +} + + +int main() { + ios::sync_with_stdio(0);cin.tie(0); + cout << setprecision(15) << fixed; + +#ifdef LOCAL + freopen("input.txt", "r", stdin); +#endif + + solve(); +}