dimanche 1 novembre 2020

Unexpected RunTime Error in C++ with Code that Works on My Local Machine

I've tried to do a few problems in the CSES problem set. The following problems both seem elementary, and they worked well on my local machine(although I would get a Time Limit Exceeded with solution 2).

Yet I got "RunTime Error" with some test cases with the online judge. I've also downloaded some test cases that happened to have "RunTime Error" and tested them, but they seem to work well too. I can't diagnose what happened, although I've submitted a lot of times, each time modifying a bit. When I compile my code on my local machine, I had the -Wall flag too.

Compiler used: g++ with c++11

  1. https://cses.fi/problemset/task/1141/ (longest distinct subarray)
#include <bits/stdc++.h>
 
typedef int64_t     int_t;
 
const int VALUE_MAX = 1000000000;
 
int main() {
    int_t n;
    std::cin >> n;
    int_t* values = new int_t[n];
    for (int_t k = 0; k < n; k++) {
        std::cin >> values[k];
    }

    bool* book = new bool[VALUE_MAX + 1];
    int_t i = 0, j = 0;
    int_t max = 0;
    while (j < n) {
        if (book[values[j]]) {
            while (values[i] != values[j]) {
                book[values[i]] = false;
                i++;
            }
            book[values[i]] = false;
            i++;
        }
        book[values[j]] = true;
        max = std::max(max, j - i + 1);
        j++;
    }
    std::cout << max << '\n';
    delete [] book;
    delete [] values;
}
  1. https://cses.fi/problemset/task/1636/ (dynamic programming)
#include <bits/stdc++.h>
 
typedef int64_t     int_t;
const int_t MOD     = 1000000007;

int main() {
    int_t n, target;
    std::cin >> n >> target;
    int_t** comb = new int_t*[target + 1];
    for (int_t i = 0; i <= target; i++) {
        comb[i] = new int_t[n + 1];
    }
    int_t* coins = new int_t[n + 1];
    for (int_t k = 1; k <= n; k++) {
        std::cin >> coins[k];
        comb[0][k] = 1;
    }
 
    for (int_t i = 1; i <= target; i++) {
        comb[i][0] = 0;
        for (int_t j = 1; j <= n; j++) {
            comb[i][j] = comb[i][j - 1];
            if (i - coins[j] >= 0) {
                comb[i][j] += comb[i - coins[j]][j];
            }
            comb[i][j] %= MOD;
        }
    }
    std::cout << comb[target][n] << '\n';
    for (int_t i = 0; i <= target; i++) {
        delete [] comb[i];
    }
    delete [] comb;
    delete [] coins;
}

I think this is a really mysterious problem... Can anyone help me figure out the problem? Thanks a lot!

Aucun commentaire:

Enregistrer un commentaire