1 solutions

  • -6
    @ 2025-7-19 22:47:02

    考虑每组括号的匹配贡献:

    • 若对于已经匹配的位置ii,其两侧有并列的括号,则新增贡献是两侧括号数量的乘积;
    • 若两侧是包起来的括号,则可以继承外面括号的贡献。

    从左括号处加入贡献,在右括号处消去贡献即可具体地求得每点上的贡献。正常加然后模即可。

    #include <bits/stdc++.h>
    using namespace std;
    #define ll long long
    const int maxn = 1e7 + 10;
    const ll mod = 1e9 + 7;
    char s[maxn]; int n, match[maxn];
    ll dp[maxn][2], ans, res;
    stack<int> st;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(0); cout.tie(0);
        cin >> (s + 1);
        n = strlen(s + 1);
        for(int i = 1;i <= n; ++i) {
            if(s[i] == '(') st.push(i);
            else if(!st.empty()) {
                match[i] = st.top();
                match[st.top()] = i;
                st.pop();
                dp[i][1] = dp[match[i]][0] = 1;
            }
        }
        for(int i = 1;i <= n; ++i)
            if(match[i] && s[i] == '(' && s[i - 1] == ')') dp[i][0] += dp[match[i - 1]][0];
        for(int i = n;i >= 1; --i)
            if(match[i] && s[i] == ')' && s[i + 1] == '(') dp[i][1] += dp[match[i + 1]][1];
        
        for(int i = 1;i <= n; ++i) {
            if(s[i] == '(') {
                if(match[i]) {
                    ans += dp[i][0] * dp[match[i]][1] % mod;
                    ans %= mod;
                    res += ans * i % mod;
                }
            } else {
                if(match[i]) {
                    res += ans * i % mod;
                    ans -= dp[i][1] * dp[match[i]][0] % mod;
                    ans %= mod;
                }
            }
        }
        cout << res % mod << '\n';
        return 0;
    }
    
    • 1

    Information

    ID
    8
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    9
    Tags
    (None)
    # Submissions
    135
    Accepted
    10
    Uploaded By