#include #include #include #include #include typedef uint64_t inclusiveLowerBound; typedef uint64_t inclusiveUpperBound; int main() { std::fstream input("input"); std::string currentLine = ""; std::multimap ranges{}; uint16_t positionOfHypen = 0; uint64_t upperBound = 0, lowerBound = 0; // Range and values are seperated by an empty \n while (std::getline(input, currentLine, '\n')) { if (currentLine == "") { break; } positionOfHypen = currentLine.find('-'); lowerBound = std::stoull(currentLine.substr(0, positionOfHypen)); upperBound = std::stoull(currentLine.substr(positionOfHypen + 1)); ranges.insert({lowerBound, upperBound}); } // First time doing this with ranges auto range = ranges.begin(); while (range != ranges.end()) { auto secondRange = range; secondRange++; while (secondRange != ranges.end()) { // 3 Possible cases bool isEndOfFirstBiggerThanSecond = range->second >= secondRange->second; // 1. Second range is fully inside First range if (isEndOfFirstBiggerThanSecond) { secondRange = ranges.erase(secondRange); continue; } // 2. Second Range's end is bigger than first, but Second's start is // smaller than first's end if (!isEndOfFirstBiggerThanSecond && range->second >= secondRange->first) { range->second = secondRange->second; secondRange = ranges.erase(secondRange); continue; } // 3. Nothing happens, they are not overlapping secondRange++; // Note: The begining of first range WILL ALWAYS be smaller than second } range++; } uint64_t password = 0; for (auto keys : ranges) { password += keys.second - keys.first + 1; // 1 is for range to be inclusive } std::cout << password << std::endl; return 0; }