Source Code
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll dp[1001][1005][5];
ll dp2[1001][1001];
ll mod = 1000000007;
ll go(int i, int v) {
    if (v<0) return 0;
    if (i==0) return (v==0);
    if (dp2[i][v]!=-1) return dp2[i][v];
    return dp2[i][v] = (go(i-1, v-1) + go(i-1, v+1))%mod;
}
int main() {
    ios_base::sync_with_stdio(0);
    int n;
    cin>>n;
    memset(dp2, -1, sizeof(dp2));
    dp[0][0][0] = 1;
    for (int i=0;i<n;i++) {
        for (int j=0;j<=n;j++) {
            for (int k=0;k<5;k++) {
                if (k<3) {
                    dp[i+1][j+1][k+1] = (dp[i][j][k] + dp[i+1][j+1][k+1])% mod;
                    if (j>0) dp[i+1][j-1][0] = (dp[i+1][j-1][0]+dp[i][j][k])%mod;
                } else {
                    if (k==3) {
                        if (j>0) dp[i+1][j-1][k+1] = (dp[i][j][k] + dp[i+1][j-1][k+1])%mod;
                        dp[i+1][j+1][k] = (dp[i][j][k] + dp[i+1][j+1][k])%mod;
                    } else if (k==4) {
                        dp[i+1][j+1][1] = (dp[i][j][k] + dp[i+1][j+1][1])%mod;
                    }
                }
            }
        }
    }
    ll ret = 0;
    for (int i = 5; i <= n; i++) {
        for (int j=1;j<=n;j++) {
            ll cur = dp[i-1][j][4];
            ret += (cur * go(n-i, j-1));
            ret %= mod;
        }
    }
    cout<<ret<<endl;
}   
Copy
Bracket Sequence RedNextCentury
GNU G++17
222 ms
48.0 MB
Accepted