1-1-1's blog

By 1-1-1, history, 19 months ago, In English

Most of the time interactive problems in codeforces do not require a very large amount of outputting, so using .flush() usually meets time constraints. However, for the Huawei ICPC 2023 Spring Challenge, the problem asks for up to 1 million different lines of output. Because of this, my code TLEs on a lot of test cases, in spite of the 15 seconds given.

As an example, the following barebone code TLEs on some test cases in each Java version:

import java.io.*;
import java.util.*;
public class A {
    public static void main(String[] args) throws IOException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw=new PrintWriter(System.out);
        StringTokenizer st=new StringTokenizer(br.readLine());
        int n=Integer.parseInt(st.nextToken());
        int size=Integer.parseInt(st.nextToken());
        int q=Integer.parseInt(st.nextToken());
        for(int i=0;i<q/2;i++){
            pw.println(1);
            pw.flush();
            pw.println(2);
            pw.flush();
        }
        if(q%2==1){
            pw.println(1);
            pw.flush();
        }
    }
}

Java 8 receives 4 TLEs, Java 11 receives 3 TLEs, and Java 17 receives 2 TLEs. This example also does not include test cases that might have TLE'd but were marked as Wrong Answer due to the requirements of the problem, and also does not factor in time needed to read input and to implement any data structures needed.

Since this code doesn't work, I was wondering if someone else with more experience with Java has a more efficient way of flushing output, or if I should just spend some time translating my code into C++. I appreciate feedback.

  • Vote: I like it
  • +8
  • Vote: I do not like it

»
19 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by 1-1-1 (previous revision, new revision, compare).

»
19 months ago, # |
  Vote: I like it +6 Vote: I do not like it

Check out templates from the following submissions

  • »
    »
    19 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    The templates increase the speed by a decent amount, thanks.