Source Code
#include "bits/stdc++.h"

using namespace std;
typedef long long ll;

const int MOD = 1e9 + 7;

inline int add(int a, int b) {
    return a + b >= MOD ? a + b - MOD : a + b;
}

int n, dp[1005][1005][32][2];

int calc1(int idx, int cnt, int mask, bool ok) {
    if (idx == n) return (cnt == 0 && ok);
    if (cnt == 1000) return 0;

    int &ret = dp[idx][cnt][mask][ok];
    if (ret != -1) {
        return ret;
    }

    ret = 0;
    int k = min(idx, 4);
    int newmask = (idx > 4 ? (mask >> 1) : mask) + (1 << k);
    ret = add(ret, calc1(idx + 1, cnt + 1, newmask, ok | (newmask == 7 && k == 4)));


    newmask = (idx > 4 ? (mask >> 1) : mask);
    if (cnt > 0) ret = add(ret, calc1(idx + 1, cnt - 1, newmask, ok | (newmask == 7 && k == 4)));

    return ret;
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> n;
    memset(dp, -1, sizeof dp);
    cout << calc1(0, 0, 0, 0);
}
Copy
Bracket Sequence OsamaX01
GNU G++17
378 ms
254.1 MB
Accepted