I share your frustration. Java is slow when using standard input and standard output, but this is not a SPOJ issue. Having tested I/O in many ways in numerous problems, I can show you how I approach input and output. This may not correct your problem, but it will improve the performance of your code.
In addition, some problems cannot be accomplished in Java. VM startup time can approach .08-.09 sec, and some problems have a time limit of .1 sec. Problem setters can set different time limits for various languages, but often don’t.
Also, the time limit for older problems can be difficult. SPOJ moved to a new platform, and many time limits were adjusted, but of course some problems cannot be accomplished in the new platform. Administrators did the best they could.
I always check how many people solved a particular problem in Java, and then decide if I will try the problem.
For output, I perform logic as follows:
PrintWriter out = new PrintWriter(System.out);
StringBuilder sb = new StringBuilder();
logic . . .
out.print(sb.toString());
out.flush();
For input, I use the parser class shown below. It is used as follows:
Parser p = new Parser(System.in); // Declare
long n = p.nextLong(); // Sample usage.
Best of luck.
static class Parser {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Parser(InputStream in) {
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while ( c <= ' ' )
c = read();
boolean neg = c == '-';
if ( neg )
c = read();
do {
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while ( c <= ' ' )
c = read();
boolean neg = c == '-';
if ( neg )
c = read();
do {
ret = ret * 10 + c - '0';
c = read();
} while ( c > ' ' );
return neg ? -ret : ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
}