2016-06-27 3 views
0

Я пытаюсь решить эту проблему:
http://codeforces.com/contest/664/problem/B
Вот мой код: http://ideone.com/fWgQEn
Я получаю ошибки Runtime на Test Case 5, несмотря на то, что мой ответ правильный, и я печатая его правильно.
Может ли кто-нибудь сказать мне, что может быть причиной этого?
Runtime Ошибка в Codeforces

#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
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++; 

вместо этого.

+0

Большое спасибо! ........ – bewithaman