2 条题解

  • 1
    @ 2026-9-5 10:30:42
    #include <iostream>
    #include <stack>
    #include <string>
    using namespace std;
    const int MOD = 10007;
    
    struct Node {
        int dp0, dp1;
        Node(int a=0,int b=0):dp0(a),dp1(b){}
    };
    
    int pri(char c){
        if(c == '(') return 0;
        if(c == '+') return 1;
        if(c == '*') return 2;
        return -1;
    }
    
    Node calc(Node x, Node y, char op){
        Node res;
        if(op == '*'){
            res.dp0 = (1LL*x.dp0*(y.dp0+y.dp1)%MOD + 1LL*x.dp1*y.dp0%MOD )% MOD;
            res.dp1 = 1LL*x.dp1 * y.dp1 % MOD;
        }else{ // '+'
            res.dp0 = 1LL*x.dp0 * y.dp0 % MOD;
            res.dp1 = (1LL*x.dp0*y.dp1 + 1LL*x.dp1*y.dp0 + 1LL*x.dp1*y.dp1) % MOD;
        }
        return res;
    }
    
    int main(){
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int L;
        string s;
        cin >> L >> s;
        stack<Node> st;
        stack<char> op;
        st.emplace(1,1); //第一个变量
        for(char ch : s){
            if(ch == '('){
                op.push(ch);
                st.emplace(1,1);
            }else if(ch == ')'){
                while(op.top() != '('){
                    char o = op.top(); op.pop();
                    Node b = st.top(); st.pop();
                    Node a = st.top(); st.pop();
                    st.push(calc(a,b,o));
                }
                op.pop(); // pop '('
            }else{ // '+' or '*'
                while(!op.empty() && pri(op.top()) >= pri(ch)){
                    char o = op.top(); op.pop();
                    Node b = st.top(); st.pop();
                    Node a = st.top(); st.pop();
                    st.push(calc(a,b,o));
                }
                op.push(ch);
                st.emplace(1,1); //新变量
            }
        }
        while(!op.empty()){
            char o = op.top(); op.pop();
            Node b = st.top(); st.pop();
            Node a = st.top(); st.pop();
            st.push(calc(a,b,o));
        }
        cout << st.top().dp0 << endl;
        return 0;
    }
    ```
    
    ```

    信息

    ID
    717
    时间
    1000ms
    内存
    256MiB
    难度
    10
    标签
    递交数
    10
    已通过
    3
    上传者