day03b.cpp (1165B)
1 #include <algorithm> 2 #include <iostream> 3 #include <sstream> 4 #include <string> 5 #include <string_view> 6 #include <vector> 7 using namespace std; 8 9 bool state = true; 10 11 int trymult(const string_view &s) { 12 if (s.substr(0, 4) != "mul(") 13 return 0; 14 15 auto t = s.substr(4, s.length()-4); 16 17 int x = 0, y = 0; 18 int i = 0; 19 for (; i < 3; i++) 20 if (t[i] >= '0' && t[i] <= '9') 21 x = (x*10) + t[i]-'0'; 22 else break; 23 if (i == 0 || t[i] != ',') 24 return 0; 25 i++; 26 int j = 0; 27 for (; j < 3; j++) 28 if (t[i+j] >= '0' && t[i+j] <= '9') 29 y = (y*10) + t[i+j]-'0'; 30 else break; 31 if (j == 0 || t[j+i] != ')') 32 return 0; 33 34 return x*y; 35 } 36 37 bool trytogglestate(bool current_state, const string_view &s) { 38 if (s.substr(0, 4) == "do()") 39 return true; 40 if (s.substr(0, 7) == "don't()") 41 return false; 42 return current_state; 43 } 44 45 int mults(const string &line) { 46 int result = 0; 47 for (auto i = line.begin(); i != line.end(); i++) { 48 string_view s(i, line.end()); 49 state = trytogglestate(state, s); 50 if (state) 51 result += trymult(s); 52 } 53 return result; 54 } 55 56 int main() { 57 string line; 58 int result = 0; 59 while (cin >> line) 60 result += mults(line); 61 cout << result << endl; 62 return 0; 63 }