-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10.cpp
82 lines (74 loc) · 2.41 KB
/
10.cpp
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
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
#include <map>
#include <vector>
#include <algorithm>
struct BracketChecker {
bool isOpen(char c) {
if (c == '(' || c == '[' || c == '{' || c == '<') return true;
return false;
}
std::map<char, char> matchingBracket_{ { ')', '(' },
{ ']', '[' },
{ '}', '{' },
{ '>', '<' } };
std::map<char, int> illegalValue_{ { ')', 3 },
{ ']', 57 },
{ '}', 1197 },
{ '>', 25137 } };
std::map<char, int> completionValue_{ { '(', 1 },
{ '[', 2 },
{ '{', 3 },
{ '<', 4 } };
};
int checkLine(const std::string& line) {
BracketChecker bc;
std::stack<char> brackets;
for (auto&& x: line) {
if (bc.isOpen(x)) brackets.push(x);
else if (brackets.top() != bc.matchingBracket_[x]) return bc.illegalValue_[x];
else brackets.pop();
}
return 0;
}
long long completeLine(const std::string& line) {
BracketChecker bc;
std::stack<char> brackets;
for (auto&& x: line) {
if (bc.isOpen(x)) brackets.push(x);
else if (brackets.top() != bc.matchingBracket_[x]) return -1;
else brackets.pop();
}
long long completionSum = 0;
while (!brackets.empty()) {
completionSum = 5 * completionSum + bc.completionValue_[brackets.top()];
brackets.pop();
}
return completionSum;
}
void partOne(std::istream& in) {
std::string line;
int illegalSum = 0;
while (std::getline(in, line)) {
illegalSum += checkLine(line);
}
std::cout << illegalSum << std::endl;
}
void partTwo(std::istream& in) {
std::string line;
std::vector<long long> completionSums;
while (std::getline(in, line)) {
long long result = completeLine(line);
if (result != -1) completionSums.push_back(result);
}
std::sort(completionSums.begin(), completionSums.end());
std::cout << completionSums[completionSums.size() / 2] << std::endl;
}
int main(int argc, char* argv[]) {
std::ifstream dataFile(argv[1]);
//partOne(dataFile);
partTwo(dataFile);
dataFile.close();
}