首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CodeForces中的运行时错误

CodeForces中的运行时错误
EN

Stack Overflow用户
提问于 2016-06-27 19:33:10
回答 1查看 183关注 0票数 0

我正试图解决这个问题:

http://codeforces.com/contest/664/problem/B

这是我的代码:http://ideone.com/fWgQEn

我得到运行时错误的测试用例5,即使我的答案是正确的,我是正确的打印它。

有人能告诉我这是什么原因吗?

代码语言:javascript
复制
#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;
}

蒂娅!!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-27 19:55:04

代码语言:javascript
复制
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[]/

试一试

代码语言:javascript
复制
str += x; i++;

而不是。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38061845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档