提问者:小点点

执行完所有代码后,返回分段错误


下面的代码是我对此链接中cp问题的解决方案:http://www.usaco.org/index.php?page=viewproblem2&cpid=761

#include<bits/stdc++.h>
using namespace std;

int main(){
    freopen("measurement.in","r",stdin);
    freopen("measurement.out","w",stdout);  

    vector<tuple<int,int,int>> records;
    
    int n; scanf("%d", &n);
    
    int day; char* cow; char sign; int change;
    for (int i=0;i<n;i++){
        scanf("%d %s %c%d", &day, cow, &sign, &change);
        
        if (sign == '-') change = -change;
        int id;
            
        if (strcmp(cow,"Bessie") == 0) id = 0;
        if (strcmp(cow,"Elsie") == 0) id = 1;
        if (strcmp(cow,"Mildred") == 0) id = 2;
    
        records.push_back(make_tuple(day,id,change)); 
    }

    sort(records.begin(),records.end());
    
    int galls[3] = {7,7,7};

    vector<int> board {0,1,2};  
    
    int num = 0;
    for (auto record : records){
        vector<int> temp = board;
        galls[get<1>(record)]+=get<2>(record);
        
        int max_o = 0;
        for(int i=0;i<3;i++)
            max_o = max(max_o,galls[i]);
    
        board.clear();
        for (int i=0;i<3;i++)
            if (galls[i] == max_o) board.push_back(i);  

        if (board.size() != temp.size()){
            num++;
        } else{
            for (int i=0;i<board.size();i++){
                if (board[i] != temp[i]){
                    num++;
                    break;
                }
            }
        }
    }

    cout << num;
}

这个解决方案返回正确的值,所有代码都被执行,但是在所有代码运行之后,会返回分段错误(核心转储)。我从来没有遇到过一个分割错误后,所有的代码都已执行,所以我很困惑,为什么会发生这种情况。有人能帮帮忙吗?

此输入文件Measurement.in如下所示:

4
7 Mildred +3
4 Elsie -1
9 Mildred -1
1 Bessie +2

共1个答案

匿名用户

原来问题出在使用C-字符串strcmp函数时。我使用字符串compare函数代替,它工作了!