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
#include <bits/stdc++.h>
using namespace std;

int value(char c) {
    return (c == '(' ? +1 : -1);
}

bool check(string res, int d, string s, int i, string t, int j) {
    if (d < 0) { return false; }
    if (i == (int)s.size() && j == (int)t.size()) {
        return d == 0;
    }

    if (i != (int)s.size() && check(res + s[i], d + value(s[i]), s, i + 1, t, j)) {
        return true;
    }    
    if (j != (int)t.size() && check(res + t[j], d + value(t[j]), s, i, t, j + 1)) {
        return true;
    }
    return false;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    auto read = []() {
        int n;
        char c;
        cin >> n >> c;
        string res;
        for (int i = 0; i < n; ++i) {
            int a;
            cin >> a;
            res += string(a, c);
            c = (c == '(' ? ')' : '(');
        }
        return res;
    };

    auto s = read(), t = read();

    int delta_s = 0;
    for (char c : s) {
        delta_s += value(c);
    }

    int ans = 0;
    for (int i = 0; i < (int)t.size(); ++i) {
        int delta_t = 0;
        for (int d = 1; i + d <= (int)t.size(); ++d) {
            delta_t += value(t[i + d - 1]);
            if (delta_t + delta_s != 0) { continue; }
            ans += check("", 0, s, 0, t.substr(i, d), 0);
        }
    }
    cout << ans << '\n';
    return 0;
}