1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
|
#include <fstream>
#include <iostream>
#include <iterator>
#include <list>
#include <ranges>
#include <string>
#include <vector>
using namespace std;
vector<int>
read_file(string_view filename)
{
fstream input{ filename };
string line;
int fid = 0;
getline(input, line);
vector<int> data;
for ( size_t i = 0; i != line.size(); ++i ) {
vector<int> values(size_t(line.at(i) - '0'), (i % 2 == 0) ? fid++ : -1);
data.insert(data.end(), values.begin(), values.end());
}
return data;
}
void
part1(const vector<int>& data)
{
vector<int> result;
auto lhs = data.begin();
auto rhs = data.end();
while ( lhs != rhs ) {
if ( *lhs != -1 ) {
result.push_back(*lhs);
}
else {
--rhs;
while ( *rhs == -1 ) {
--rhs;
}
result.push_back(*rhs);
}
++lhs;
}
long sum = 0;
for ( size_t i = 0; i != result.size(); ++i ) {
sum += long(i) * result.at(i);
}
cout << sum << endl;
}
void
part2(const vector<int>& data)
{
// id, pos, len
vector<tuple<int, size_t, size_t>> files;
// pos, len
list<tuple<size_t, size_t>> spaces;
for ( size_t i = 0; i != data.size(); ) {
// skip space
auto j = i;
while ( j != data.size() && data.at(j) == -1 ) {
++j;
}
if ( i != j ) {
spaces.emplace_back(i, j - i);
}
i = j;
while ( j != data.size() && data.at(i) == data.at(j) ) {
++j;
}
if ( i != j ) {
files.emplace_back(data.at(i), i, j - i);
}
i = j;
}
for ( auto& file: std::ranges::reverse_view(files) ) {
for ( auto it = spaces.begin(); it != spaces.end(); ++it ) {
if ( get<0>(*it) >= get<1>(file) ) {
spaces.erase(it, spaces.end());
break;
}
if ( get<1>(*it) >= get<2>(file) ) {
// update pos
get<1>(file) = get<0>(*it);
// update space len
get<1>(*it) -= get<2>(file);
// update space pos
get<0>(*it) += get<2>(file);
if ( get<1>(*it) == 0 ) {
spaces.erase(it);
}
break;
}
}
}
long sum = 0;
for ( const auto& [fid, pos, size]: files ) {
for ( size_t x = pos; x != pos + size; ++x ) {
sum += long(x) * fid;
}
}
cout << sum << endl;
}
int
main()
{
auto data = read_file("data/day09.txt");
part1(data);
part2(data);
}
|