advent-of-code/2023/8/main-2.cpp
eriedaberrie fd38485e1b cleanup
2023-12-09 20:54:33 -08:00

55 lines
1.1 KiB
C++

#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
string instructions;
getline(cin, instructions);
cin.ignore(1);
unordered_map<string, pair<string, string>> locs;
string line;
while (getline(cin, line)) {
locs[line.substr(0, 3)] = make_pair(line.substr(7, 3), line.substr(12, 3));
}
vector<string> starts;
for (auto& loc : locs) {
if (loc.first[2] == 'A')
starts.push_back(loc.first);
}
unsigned long amounts[starts.size()];
memset(amounts, 0, starts.size() * sizeof(unsigned long));
long n = 0;
unsigned int done = starts.size();
while (done > 0) {
for (unsigned int i = 0; i < starts.size(); i++) {
if (amounts[i] != 0)
continue;
if (instructions[n % instructions.length()] == 'L')
starts[i] = locs[starts[i]].first;
else
starts[i] = locs[starts[i]].second;
if (starts[i][2] == 'Z') {
amounts[i] = n + 1;
done--;
}
}
n++;
}
unsigned long val = amounts[0];
for (unsigned int i = 1; i < starts.size(); i++) {
val = lcm(val, amounts[i]);
}
cout << val << '\n';
}