CodeForces中的运行时错误

时间:2016-06-27 19:33:11

标签: algorithm

我正在努力解决这个问题:
http://codeforces.com/contest/664/problem/B
这是我的代码:http://ideone.com/fWgQEn
我在测试用例5上遇到运行时错误,即使我的答案是正确的,我正在正确打印它 谁能告诉我这是什么原因?

#include<bits/stdc++.h>

using namespace std;

int main(){
    int i = 0, pos = 1, neg = 0, n;
    string str;
    char x;
    while(1){
        cin >> x;
        if(x == '=') break;
        else if (x == '?') continue;
        else if (x == '+') pos++;
        else if (x == '-') neg++;
        str[i++] = x;
    }
    str[i] = '\0';
    // cout << str[0] << str[1] << str.size() << endl;
    cin >> n;

    if (!(pos * n - neg >= n && pos - neg * n <= n))
    cout << "Impossible" << endl;

    else{
        cout << "Possible\n";
        int neg_sum, pos_sum;
        for (int i = neg; i <= neg * n; i++){
            pos_sum = n + i;
            if(pos_sum <= pos * n && pos_sum >= pos) {
                neg_sum = i; pos_sum = n + i;
                break;
            }
        }
        // cout << str.size() << endl;
        // cout << pos_sum << " " << neg_sum << endl;
        int pos_count = 1, neg_count = 0;
        for(int i = -1 ; i < pos + neg - 1; i++){
            // cout << "i " << i << " " << str[i] <<endl;
            if(!(i + 1)){
                if(pos == 1) cout << pos_sum << " ";
                else cout << pos_sum / (pos - 1) << " ";
            }

            else{
                if(str[i] == '+'){
                    if(pos_count++ != pos -1) cout << "+ "<< pos_sum / (pos - 1) << " ";
                    else cout << "+ "<< pos_sum  % (pos - 1) << " ";
                }
                else{
                    if(neg == 1) cout << "- " << neg_sum << " ";
                    else if(neg_count++ != neg -1) cout << "- "<< neg_sum / (neg - 1) << " ";
                    else cout << "+ "<< neg_sum % (neg - 1) << " ";
                }
            }
        } 
        cout << "= " << n;
    }
    return 0;
}

TIA !!

1 个答案:

答案 0 :(得分:1)

string str;
char x;
while(1){
    cin >> x;
    if(x == '=') break;
    else if (x == '?') continue;
    else if (x == '+') pos++;
    else if (x == '-') neg++;
    str[i++] = x;
}

我认为至少str[i++] = x;会遇到未分配的空格并导致未定义的行为。看到 http://www.cplusplus.com/reference/string/string/operator[]/

尝试

str += x; i++;

代替。