1

I am trying out http://www.spoj.com/problems/BRCKTS/ , I got the logic but this gives segmentation fault upon entering the string. I think the problem is with inserting the characters in the array, can't figure it out.

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;
}
4

1 回答 1

0

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

于 2013-09-14T17:27:03.833 回答