public String toString(){ return"" + id + " " + exam; } }
publicstaticvoidmain(String[] args){ Scanner in = new Scanner(new BufferedInputStream(System.in)); while (in.hasNextInt()) { int N = in.nextInt(); Stu[] stus = new Stu[N + 1]; for (int i = 1; i <= N; i++) { long id = in.nextLong(); int test = in.nextInt(); int exam = in.nextInt(); stus[test] = new Stu(id, exam); }
int M = in.nextInt(); for (int i = 1; i <= M; i++) { System.out.println(stus[in.nextInt()]); } } } }
public String toString(){ return"" + id + " " + exam; } }
publicstaticvoidmain(String[] args){ Scanner in = new Scanner(new BufferedInputStream(System.in)); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); // 使用 PrintWriter,并使用了缓冲流加快输出 while (in.hasNextInt()) { int N = in.nextInt(); Stu[] stus = new Stu[N + 1]; for (int i = 1; i <= N; i++) { long id = in.nextLong(); int test = in.nextInt(); int exam = in.nextInt(); stus[test] = new Stu(id, exam); }
int M = in.nextInt(); for (int i = 1; i <= M; i++) { out.println(stus[in.nextInt()]); // 输出 } out.flush(); // 将读到的内容从缓冲区输出 } } }
这样总该没问题了吧
WTF!?说实话,当时我都觉得这道题就是来坑 Java 选手的 🙃
Google 一下
没办法,只能请教 Google 大爷了,Google 搜索 Java in ACM TLE, how to improve input and output speed (原谅我的英语渣😅
BufferedReader – (fast, but not recommended as it requires lot of typing): The Java.io.BufferedReader class reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. With this method we will have to parse the value every time for desired type. Reading multiple words from single line adds to its complexity because of the use of Stringtokenizer and hence this is not recommended. This gets accepted with a running time of approx 0.89 s.but still as you can see it requires a lot of typing all together and therefore method 3 is recommended.
public String toString(){ return"" + id + " " + exam; } }
publicstaticvoidmain(String[] args){ FastReader in = new FastReader(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int N = in.nextInt(); Stu[] stus = new Stu[N + 1]; for (int i = 1; i <= N; i++) { long id = in.nextLong(); int test = in.nextInt(); int exam = in.nextInt(); stus[test] = new Stu(id, exam); }
int M = in.nextInt(); for (int i = 1; i <= M; i++) { out.println(stus[in.nextInt()]); } out.flush(); }
在这篇回答的最后,答主还提到了提高输出速度的方法,就是我之前提到的使用 PrintWriter 来代替传统的 System.out.println(),同时要记得在所有输出操作结束时调用 flush() 方法,但是过于频繁的调用也有可能引发 TLE
总结
题目本身不难,一般写工程的时候也没有太刻意去提高 I/O 速度,当然我觉的也是我修为不够,还没到那一步,所以在遇到这一道题时,碰到 TLE 的确有点不知所措,我觉得这也算是一个考察点吧,正好了解了如何提高 Java I/O 速度的一点小技巧。
一般情况下,用 Scanner in = new Scanner(new BufferedInputStream(System.in));做输入是足够的,因为写过的题也不少,碰到这种因为输入导致的超时也是第一次,如果某题卡时间真的很紧,那么再考虑用自定义类包装 BufferedReader 的方式,毕竟这种方式虽快,但是代码量也多了不少。
同样的,如果时间卡的不紧的话,用传统的 System.out.println() 我觉得也能应付,当然为了防止输出问题导致超时的话,可以使用 PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); 的方式,要记得在一轮操作做完后调用 flush() 方法清空缓冲区,不然会输出不了结果。