#include <stdio.h>
#include <string.h>

int scoreOfParentheses(char *s) {
    int stack[50], top = -1;
    stack[++top] = 0;  // base score

    for (int i = 0; s[i] != '\0'; i++) {
        if (s[i] == '(') {
            stack[++top] = 0;   // push new score frame
        }
        else if (s[i] == ')') {
            if (top < 1) return -1;  // unbalanced
            int v = stack[top--];    // inner score
            int w = stack[top];
            stack[top] = w + (v == 0 ? 1 : 2 * v);
        }
        else {
            return -1;  // invalid character
        }
    }