一次由 System.out.println() 引起的 MLE&TLE


P5461 赦免战俘,看题第一感觉就是递归处理,不出意外的成功写出了递归解法,然后高高兴兴的就在 OJ 上提交,然后就是莫名其妙的 MLE

原始代码:

// 递归函数
public static void f(int[][] a, int x1, int x2, int y1, int y2) {
	if (x2-x1==1 && y2-y1==1) {
		a[x1][y1] = 0;
		return;
	} else {
		for (int i = x1; i <= (x2-x1)/2+x1; ++i) {
			for (int j = y1; j <= (y2-y1)/2+y1; ++j) {
				a[i][j] = 0;
			}
		}
		f(a, (x2-x1)/2+x1+1, x2, y1, (y2-y1)/2+y1);
		f(a, x1, (x2-x1)/2+x1, (y2-y1)/2+y1+1, y2);
		f(a, (x2-x1)/2+1+x1, x2, (y2-y1)/2+1+y1, y2);
	}
}

第一次尝试结果:
在这里插入图片描述

一次由 Scanner(System.in) 引起的 TLE)。
  • 频繁输入调用使用 StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
  • 频繁输出调用使用 PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
  • 可手动调用 flush() 方法输出缓冲区,但是过于频繁的调用也有可能引发 TLE。
  • 一般情况下,使用传统的 System.out.println(); 我觉得足以应付,遇到频繁输出时再使用改进方法。当然为了防止输出问题导致 TLE&MLE 的话,可以直接使用 PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); 记得在最后调用 flush() 方法清空缓冲区,不然会输出不了结果。
  • 最后记得关闭输入输出流,养成一个好习惯,这样即使忘记清空缓冲区,也会因为关闭输出流而自动清空缓冲区。