This is my code:
#include <bits/stdc++.h>
using namespace std;
int main() {
freopen("bcount.in", "r", stdin);
freopen("bcount.out", "w", stdout);
int n, q;
cin >> n >> q;
vector<int> holsteins(n);
vector<int> guernseys(n);
vector<int> jerseys(n);
for (int i = 0 ; i < n ; i++) {
holsteins[i+1]=holsteins[i];
guernseys[i+1]=guernseys[i];
jerseys[i+1]=jerseys[i];
int a;
cin >> a;
if (a==1) holsteins[i+1]++;
else if (a==2) guernseys[i+1]++;
else jerseys[i+1]++;
}
for (int i = 0; i < q ; i++) {
int a, b;
cin >> a >> b;
cout << holsteins[b]-holsteins[a-1] << " " << guernseys[b]-guernseys[a-1] << " " << jerseys[b]-jerseys[a-1] << "\n";
}
return 0;
}
When I run it, it fails to pass the sample case and the official grader says that there was a runtime error or memory fail. I suspected it had something w/ input output but there wasn't. What's wrong here?
There are multiple bugs in the shown code, assuming that it even compiles, because:
This is a non-standard header file. On some C++ compilers the shown code won't even compile. Assuming that the shown code compiles:
This input is not checked for validity. Invalid or negative input results in undefined behavior.
This results in undefined behavior when
iisn-1, soi+1isn, and this assigns toholsteins[n], which does not exist.Same bug here, undefined behavior when accessing a nonexistent value in the vector.
Continuation/variation of the first bug. Invalid or negative input results in undefined behavior.
All of the above bugs, combined. Undefined behavior due to invalid or negative input, or due to access to nonexistent vector values (when
boraisnor greater).Those are all the reason I could see why the shown code will not work correctly due to undefined behavior.