c++ - 在 spoj 上解决 BRCKTS

标签 c++

我正在尝试 http://www.spoj.com/problems/BRCKTS/ ,我得到了逻辑,但这在输入字符串时会出现段错误。我认为问题在于在数组中插入字符,无法弄清楚。

int main() {
        int t = 10;
        int l = 1;
        do{
            int length_bracket;
            char d;
            cin>>length_bracket;
            vector<char> word;
        string output;

        for( int i =0; i<length_bracket; i++) {
            cin.get(d);
            word.push_back(d);
        }

        int num_operations;
        cin>>num_operations;
        do{
            int n;
            cin>>n;

            if(n == 0) {

                if(word[0] == ')' || word[length_bracket] == '(') {

                    output = output + "NO" + '\n';
                }
                else {
                    int l1 = 0; int l2 = 0;
                    for(int i=0; i<length_bracket; i++) {
                        if(word[i] == ')') {
                            l1 = l1+1;
                        }
                        else {
                            l2 = l2+1;
                        }
                    }
                    if(l1 == l2 && l1 != 0 && l2 != 0 ) {
                        output = output + "YES" + '\n';
                    }
                    else {
                        output = output + "NO" + '\n';
                    }
                }
            }

            else {
                if(word[n-1] == '(')
                    word[n-1] = ')';
                else
                    word[n-1] = '(';
            }
            num_operations--;
        }while(num_operations);

        cout<<"Test"<<l<<endl;
        l++;        

        cout<<output;

        t--;
    }while(t);

    return 0;
}

最佳答案

只是简单地浏览了一下代码,我发现您正在访问 word[length_bracket]word 仅包含 length_bracket 个字符,因此您应该改为检查 word[length_bracket-1]

关于c++ - 在 spoj 上解决 BRCKTS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18803212/

相关文章:

c++ - 函数指针问题

c++ - 从protobuf继承C++类

c++ - 如何从 Windows 中提取 Windows OEM key

c++ - 不同大小的着色器存储缓冲区内容 "transfered"到数组缓冲区

Visual Studio 2005 中的 C++ 错误检测

c++ - 这是 C++ 中多态性的正确场景吗?

c++ - 为什么 vector 被视为按值传递,即使它是通过 const 引用传递的?

c++ - 将 vector 投影到单位框的有效方法

c++ - 我如何检查该函数是否真的获得了一个定义为 const 的变量?

c++ - 屏幕休眠时的 AFX_WM_DRAW2D 消息