Search code examples
c++prefix-sum

Why does my code to USACO Silver Breed Counting not work?


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?


Solution

  • There are multiple bugs in the shown code, assuming that it even compiles, because:

    #include <bits/stdc++.h>
    

    This is a non-standard header file. On some C++ compilers the shown code won't even compile. Assuming that the shown code compiles:

        cin >> n >> q;
        vector<int> holsteins(n);
    

    This input is not checked for validity. Invalid or negative input results in undefined behavior.

        for (int i = 0 ; i < n ; i++) {
            holsteins[i+1]=holsteins[i];
    

    This results in undefined behavior when i is n-1, so i+1 is n, and this assigns to holsteins[n], which does not exist.

            guernseys[i+1]=guernseys[i];
            jerseys[i+1]=jerseys[i];
    

    Same bug here, undefined behavior when accessing a nonexistent value in the vector.

            int a;
            cin >> a;
            if (a==1) holsteins[i+1]++;
    

    Continuation/variation of the first bug. Invalid or negative input results in undefined behavior.

            int a, b;
            cin >> a >> b;
            cout << holsteins[b]-holsteins[a-1] << " " << guernseys[b]-
    

    All of the above bugs, combined. Undefined behavior due to invalid or negative input, or due to access to nonexistent vector values (when b or a is n or greater).

    Those are all the reason I could see why the shown code will not work correctly due to undefined behavior.