Kuntal Majumder Kuntal Majumder - 2 months ago 18
C++ Question

Code for calculating jobs remaining for Chef

Recently while practicing in codechef I came across this problem.

Everything went fine , it was an easy problem , simple logic , well it took no more than 10 mins to cook the code and it also ran fine in my machine but giving a

Runtime Error(SIGSEGV)
when I try to execute it in codechef.

I thought there might some problem with the arrays I have used , no help, i tried to debug it with
gdb
it also shows well , i even tried big test cases like about 1000 or so , it ran fine , then why its showing a runtime error in codechef?

Here is the Code:

#include <iostream>

int main(){
int testCases;
std::cin >> testCases;
while(testCases--)
{
int jobs,n;
std::cin >> jobs >> n;
int doneJobs[n];
for(int i = 0; i < n; i++)
{
std::cin >> doneJobs[i];
}
bool todoJobs[jobs] = {false};
for(int i = 0; i < n; i++)
{
todoJobs[doneJobs[i] - 1] = true;
}
bool toSkip = false;
for(int i = 0; i < jobs; i++)
{
if(todoJobs[i] == false)
{
if(toSkip == false)
{
std::cout << i + 1 << ' ';
toSkip = true;
todoJobs[i] = true;
}
else
{
toSkip = false;
}
}
}
std::cout << std::endl;
for(int i = 0; i < jobs; i++)
{
if(todoJobs[i] == false)
{
std::cout << i+1 << ' ';
}
}
std::cout << std::endl;
}
return 0;
}


Edit :
Thanks to @DominiqueLorre for pointing out that some random values entered can result in an
Runtime Error
, but still I am getting it here is my edited code:

#include <iostream>

int main(){
int testCases;
std::cin >> testCases;
while(testCases--){
int jobs,n;
std::cin>>jobs>>n;
bool todoJobs[jobs] = {false};
for(int i=0;i<n;i++){
int testJob;
std::cin >> testJob;
todoJobs[testJob-1] = true;
}
bool toSkip = false;
for(int i=0;i<jobs;i++){
if(todoJobs[i] == false){
if(toSkip == false){
std::cout << i+1 << ' ';
toSkip = true;
todoJobs[i] = true;
}else{
toSkip = false;
}
}
}
std::cout << std::endl;
for(int i=0;i<jobs;i++){
if(todoJobs[i] == false){
std::cout << i+1 << ' ';
}
}
std::cout << std::endl;
}
return 0;
}

Answer

According to problem definition, it's stated that n,m satisfying 0 ≤ m ≤ n ≤ 1000 (in your code n => jobs, m => n), thus test case 0 0 is valid. However, the following snippet will causing runtime error if jobs is 0, since C++14 does not allow declaration of zero-sized dynamic array.

bool todoJobs[jobs] = {false};

Add statement to check the value of jobs before array allocation.

if (jobs <= 0) continue;