aoc

My solutions for the Advent of Code
git clone https://git.tronto.net/aoc
Download | Log | Files | Refs | README

day09b.cpp (994B)


      1 #include <algorithm>
      2 #include <iostream>
      3 #include <map>
      4 #include <ranges>
      5 #include <set>
      6 #include <sstream>
      7 #include <string>
      8 #include <string_view>
      9 #include <vector>
     10 using namespace std;
     11 
     12 int main() {
     13 	vector<long long> a;
     14 	vector<pair<int, int>> freesp, file;
     15 	char c;
     16 	for (int id = 0; cin >> c; id++) {
     17 		if (id % 2 == 1)
     18 			freesp.push_back(make_pair(a.size(), c-'0'));
     19 		else
     20 			file.push_back(make_pair(a.size(), c-'0'));
     21 		for (int j = 0; j < c-'0'; j++)
     22 			a.push_back(id % 2 == 0 ? id/2 : -1); // -1 = space
     23 	}
     24 
     25 	for (auto& p : file | views::reverse) {
     26 		for (auto& f : freesp) {
     27 			if (f.first >= p.first) break;
     28 			if (f.second >= p.second) {
     29 				for (int k = 0; k < p.second; k++) {
     30 					a[f.first+k] = a[p.first+k];
     31 					a[p.first+k] = -2;
     32 				}
     33 				f.first += p.second;
     34 				f.second -= p.second;
     35 				break;
     36 			}
     37 		}
     38 	}
     39 
     40 	long long checksum = 0;
     41 	for (long long i = 0; i < (long long)a.size(); i++)
     42 		if (a[i] >= 0)
     43 			checksum += i*a[i];
     44 	cout << checksum << endl;
     45 
     46 	return 0;
     47 }