advent-of-code/2024/5/main-2.cpp
2024-12-07 21:59:13 -08:00

54 lines
904 B
C++

#include <bits/stdc++.h>
using namespace std;
map<int, set<int>> order;
bool ordered(vector<int>& elems) {
for (int i = 0; i < elems.size(); i++) {
if (order.contains(elems[i])) {
for (int j = 0; j < i; j++) {
if (order[elems[i]].contains(elems[j])) {
int x = elems[i];
elems[i] = elems[j];
elems[j] = x;
return false;
}
}
}
}
return true;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
string line;
while (getline(cin, line) && !line.empty()) {
istringstream l(line);
int a, b;
l >> a;
l.ignore();
l >> b;
order[a].insert(b);
}
int ret = 0;
while (getline(cin, line) && !line.empty()) {
istringstream l(line);
int x;
vector<int> elems;
while (l >> x) {
elems.push_back(x);
l.ignore();
}
if (ordered(elems)) {
continue;
}
while (!ordered(elems));
ret += elems[elems.size() / 2];
}
cout << ret << '\n';
}