Runtime Error (NZEC) in PRMQ

I am getting Run Time (NZEC) Error in the Codechef June Challenge 2017 question Chef and Prime Queries. The link to the question is : Chef and Prime Queries.

For subtask 1, it is working fine. Can anyone help me? Link to my solution is : Solution

I get a runtime error running your code with this input :

4 
2 3 4 5
2
1 3 2 3
1 4 2 5

See, there is a space after the first number which makes your parsing to int throw a NumberFormatException. Try removing any useless spaces before parsing to int and it might solve your problem.

It is not an input problem. I always take input using BufferedReader class. I have solved this problem with some another approach using same input method but I am still not understand why I am getting Runtime Error using this method.

Can you give some comments and variable description? Its hard to figure out what you are doing with multiple arrays and variables.

int []a = new int[n];
Arrays.sort(arr,new Comparator<int []>(){
public int compare(int []a, int []b){
if(a[0] > b[0]){
return -1;
}else if(a[0] < b[0]){
return 1;
}else{
if(a[4] == 0){
return -1;
}else{
return 1;
}
}
}
});

I don’t really know java but, if n < 4, you accessing a[4] should raise an exception and hence the NZEC.

Arrays.sort(arr, new comparator()); is used to just sort the 2D Array on the basis of some column. Here I am sorting it on the basis of first column of arr Array and if value of first column is same then on basis of fifth column. So this is not the issue.

ind1 = 0 when x is less than or equal to the first prime. In this case, accessing b[ind1 - 1] would lead to a runtime error.

I am accessing b[ind1-1] only if ind1 > 0. Please check the code once again.

The code link you provided has an illegal argument exception that I caught with try catch blocks.

The issue is the way you are using sort function.
Here is the code submission that confirms the error source is the sort function:

https://www.codechef.com/viewsolution/14243689

2 Likes

My bad, indeed you had that check.

Thank you very much for telling this. Do you know why the sort function throws an exception?

Following from @virresh’s solution, I was able to get AC for subtask 2 by changing:

if(a[4] == 0){
	return -1;
}else{
	return 1;
}

to this:

if(a[4] == 0){
	return -1;
}else if(b[4] == 0){
	return 1;
}else{
	return 0;
}

I think this is because Java is strict that the compare function must be transitive. It has been discussed in StackOverflow (link).

As expected, the NZEC was removed after such change (see this submission). However, after the fix, your solution is still WA for the last subtask so you might want to focus on that.

Hope that was helpful :slight_smile:

1 Like

Thank you for the stackoverflow link. From next time , I will write my own sort function.

//