Search code examples
c++algorithmarray-algorithms

online judge problems program c++


#include <iostream>

using namespace std;

const int TMAX = 2000000;

int num_chupiguays(const int a[], int n) {
    int suma  = 0;
    int resul = 0;
    for (int i = 0; i < n; i++) {
        if (i > 0 && a[i] % suma == 0) {
            resul++;
        } --> gives an run error in an online judge
/*if (i > 0 && suma != 0 &&  a[i] % suma == 0) {
            resul++;
        }*/ --> gives a wrong answer
        suma += a[i];
    }
    return resul;
}

void lee_vector(int a[], int& n) {
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
}

int main() {
    static int a[TMAX];
    int n;
    do {
        lee_vector(a, n);
        if (n >= 0) {
            cout << num_chupiguays(a, n) << endl;
        }
    } while (n != -1);
}

The program counts how many numbers in the array are multiples of the sum of previous elements. It passes all cases but I keep getting run-error in an online judge. Any help?


Solution

  • The program counts how many numbers in the array are multiples of the sum of previous elements. It passes all cases but I keep getting run-error in an online judge. Any help?

    Break the test into two parts. The first test is a special case that was identified in the problem description:

    Note that the only int that is a multiple of 0 is 0 itself.

    So long as variable suma remains at 0, you have a special case. Note that the value of loop counter i is irrelevant to this test.

    if (suma == 0)
    {
        if (a[i] == 0)
            ++resul;
    }
    

    Otherwise, the second test uses the mod operator to check whether a[i] leaves a remainder after division by suma:

    if (suma == 0)
    {
        if (a[i] == 0)
            ++resul;
    }
    else if (a[i] % suma == 0)
    {
        ++resul;
    }
    

    Dropping these tests into the function written by the OP, while keeping everything else the same, gives you this function:

    int num_chupiguays(const int a[], int n)
    {
        int suma = 0;
        int resul = 0;
        for (int i = 0; i < n; i++)
        {
            if (suma == 0)
            {
                if (a[i] == 0)
                    ++resul;
            }
            else if (a[i] % suma == 0)
            {
                ++resul;
            }
            suma += a[i];
        }
        return resul;
    }
    

    Here is the output from several test runs. The last two are the "problem" tests that were identified in the comments. Happily, they are now behaving:

    array: [], num_chupiguays: 0
    array: [0], num_chupiguays: 1
    array: [1], num_chupiguays: 0
    array: [1,2], num_chupiguays: 1
    array: [2,3,5], num_chupiguays: 1
    array: [2,4,7,26,5], num_chupiguays: 2
    array: [1,1,1,6,2,44], num_chupiguays: 3