我目前在USACO做一个基本的模拟问题。我很确定我已经正确地完成了这个问题的算法,然而,当我试图给数组赋值时,我得到了错误:run: line 1: 3 Segmentation fault (core dumped) LD_LIBRARY_PATH=/usr/local/gcc-9.2.0/lib64 ./a.out
。这是我的代码:
#include <iostream>
#include<string>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include<vector>
#include <cmath>
#include <array>
using namespace std;
void setIO(string s) { // the argument is the filename without the extension
freopen((s+".in").c_str(),"r",stdin);
freopen((s+".out").c_str(),"w",stdout);
}
int main() {
// setIO("speeding");
string new_signal = "";
int m, n; cin >> m >> n;
int arr1[n+m] = {0};
int arr2[n+m] = {0};
for(int i = 0; i < n+m; i++) {
int a, b; cin >> a >> b;
arr1[i] = a;
arr2[i] = b;
// cout << n+m;
}
int road_limits[100] = {0};
int counter = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < arr1[i]; j++) {
road_limits[counter] = arr2[i];
counter++;
}
}
counter = 0;
int max_over_limit = -200;
for(int i = n; n < n+m; n++) {
for(int j = 0; j < arr1[i]; j++) {
if((arr2[i] - road_limits[counter]) > max_over_limit){
max_over_limit = (arr2[i] - road_limits[counter]);
}
counter++;
}
}
cout << max_over_limit;
return 0;
}
用print语句调试后,似乎我的代码在第一个for循环的某个地方得到了分割错误,我在那里分配了arr1和arr2的值(没有cout
语句运行过该点)。但我不明白为什么会这样。我对使用c++比较陌生,所以是否有我误解的东西导致了这个错误?
road_limits的大小为100,counter可以超过100数组边界可以在几个地方交叉:
road_limits[counter] = arr2[i];
if((arr2[i] - road_limits[counter]) > max_over_limit){
max_over_limit = (arr2[i] - road_limits[counter]);
取决于你想做什么:需要检查,例如:
for(int i = n; i < 100 && i < n+m; i++) {
for(int j = 0; j < arr1[i]; j++) {
if((arr2[i] - road_limits[counter]) > max_over_limit){
max_over_limit = (arr2[i] - road_limits[counter]);
}
counter++;
}
}