HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

"Sherlock and queries" challenge

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
andquerieschallengesherlock

Problem

I'm writing some Java code for some pretty large datasets, in a puzzle I'm trying to solve. The output is correct, but the program doesn't run within the time limit for all the test cases. I've tried a number of optimizations, but can't think about how to improve it. I'd appreciate your suggestions.

The puzzle is here.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer(br.readLine());
int N = Integer.parseInt(tok.nextToken());
int M = Integer.parseInt(tok.nextToken());
long[] A = new long[N];
int[] B = new int[M];
long[] C = new long[M];    
tok = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) A[i] = Long.parseLong(tok.nextToken());
tok = new StringTokenizer(br.readLine());
for (int i = 0; i < M; i++) B[i] = Integer.parseInt(tok.nextToken());
tok = new StringTokenizer(br.readLine());
for (int i = 0; i < M; i++) C[i] = Long.parseLong(tok.nextToken());
br.close();

for (int i = 0; i < M; i++) {
    for (int j = B[i] - 1; j < N; j += B[i]) {
        A[j] = (A[j] * C[i]) % 1000000007;
    }
}
for (long l : A) System.out.print(l + " ");

Solution

This is one of the beefs I have with online judging systems like this..... it is not testing the algorithm, or anything like that. Instead, consider doing the very last line like:

// the longest value will be 11 chars long because % 1000000007 + " "
StringBuilder sb = new StringBuilder(N * 11);
for (long l : A) {
    sb.append(l).append(" ");
}
System.out.print(sb.toString());


A single println is almost always N times faster than N printlns.

If that does not make it work in time, then consider reading the entire System.in in to a buffer, and parsing it from the buffer.

Code Snippets

// the longest value will be 11 chars long because % 1000000007 + " "
StringBuilder sb = new StringBuilder(N * 11);
for (long l : A) {
    sb.append(l).append(" ");
}
System.out.print(sb.toString());

Context

StackExchange Code Review Q#58095, answer score: 4

Revisions (0)

No revisions yet.