#include #include #include #define INPUT_MAX 1024*1024 #define MAX_MATCHES 3 int main() { char *p, *buf, c; buf = calloc(INPUT_MAX, sizeof(char)); p = buf; regex_t regex, doit, dont; regmatch_t matches[MAX_MATCHES]; regcomp(®ex, "mul\\(([0-9]{1,3}),([0-9]{1,3})\\)|do\\(\\)|don't\\(\\)", REG_EXTENDED); while ((c = getchar()) != EOF) { *p++ = c; } int sum = 0, sum2 = 0; int enabled = 1; p = buf; for (;;) { if(regexec(®ex, p, MAX_MATCHES, matches, 0)) { break; } // mul matched if (matches[1].rm_so != -1) { // There will be 3 matches: 1 for the whole regex and 2 for the capture groups int a, b; sscanf(p + matches[1].rm_so, "%i", &a); sscanf(p + matches[2].rm_so, "%i", &b); sum += a * b; if (enabled) { sum2 += a * b; } } else { if (*(p + matches[0].rm_so + 2) == 'n') { enabled = 0; } else { enabled = 1; } } p += matches[0].rm_eo; } regfree(®ex); free(buf); printf("%i\n", sum); printf("%i\n", sum2); }