Created
December 17, 2024 18:44
-
-
Save maudzekod4000/91ebfa9e5267efde729142a11360abc1 to your computer and use it in GitHub Desktop.
C++ Pak machka na 2024 AOC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <string> | |
#include <ctype.h> | |
#include <vector> | |
#include <algorithm> | |
#include <unordered_map> | |
#include <sstream> | |
#include <regex> | |
#include <utility> | |
using namespace std; | |
// Complexity of N^2 * M ? No problem for C++! | |
bool checkForValidity(std::vector<std::pair<int, int>> rules, std::vector<int> pages) | |
{ | |
// check all pairs of pages | |
for (int i = 0; i < pages.size(); i++) { | |
for (int j = i + 1; j < pages.size(); j++) { | |
int a = pages[i]; | |
int b = pages[j]; | |
for (int k = 0; k < rules.size(); k++) { | |
auto rule = rules[k]; | |
if (rule.first == b && rule.second == a) { | |
return false; | |
} | |
} | |
} | |
} | |
return true; | |
} | |
void napraiGiPravilnoNanagore(std::vector<std::pair<int, int>> rules, std::vector<int>& pages) | |
{ | |
// check all pairs of pages | |
for (int i = 0; i < pages.size(); i++) { | |
for (int j = i + 1; j < pages.size(); j++) { | |
int a = pages[i]; | |
int b = pages[j]; | |
for (int k = 0; k < rules.size(); k++) { | |
auto rule = rules[k]; | |
if (rule.first == b && rule.second == a) { | |
// This is not correct order. | |
// FIXEM! | |
std::swap(pages[i], pages[j]); | |
} | |
} | |
} | |
} | |
} | |
int main() | |
{ | |
ifstream infile("input.txt"); | |
if (!infile.is_open()) { | |
cout << "File prob\n"; | |
return -1; | |
} | |
string line; | |
std::vector<std::pair<int, int>> rules; | |
while (infile.good()) { | |
getline(infile, line); | |
if (line.empty()) break; | |
int x, y; | |
auto pos = line.find('|'); | |
std::string firstNumS = line.substr(0, pos); | |
std::string secondNumS = line.substr(pos + 1); | |
int page1 = std::stoi(firstNumS); | |
int page2 = std::stoi(secondNumS); | |
rules.emplace_back(page1, page2); | |
} | |
int total = 0; | |
while (infile.good()) { | |
getline(infile, line); | |
if (line.empty()) break; | |
std::vector<int> pages; | |
char separator = ','; | |
int offset = 0; | |
int pos; | |
do { | |
pos = line.find(separator, offset); | |
std::string str = line.substr(offset, pos - offset); | |
pages.push_back(std::stoi(str)); | |
offset = pos + 1; | |
} while (pos != std::string::npos); | |
auto isvalid = checkForValidity(rules, pages); | |
if (!isvalid) { | |
napraiGiPravilnoNanagore(rules, pages); | |
int mid = pages[pages.size() / 2]; | |
total += mid; | |
} | |
} | |
std::cout << total << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment