mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4mobile wallpaper 5mobile wallpaper 6
539 字
3 分钟
【算法笔记】(三)处理输入和输出
2026-01-09
统计加载中...

Java ACM 输入输出风格整理(推荐写法)#

ACM/竞赛题里,输入量大、格式多变,写法上更强调:

  • 读入快(避免 Scanner
  • 输出集中(用缓冲输出)
  • 变量/数组尽量复用(减少频繁创建对象)

下面按两类常见输入方式整理。


1. ACM 风格:用 StreamTokenizer 按数字读#

适用场景:题目输入由大量数字组成,比如:

  • 先给 n m
  • 再给 n × m 个数字(矩阵、图、数组等)

示例输入:读入一个 n 行 m 列矩阵#

3 3
1 2 3
1 2 3
3 2 1

推荐代码#

import java.io.*;
import java.util.*;
public class Main {
// 尽量使用全局静态空间(避免频繁 new)
public static int[][] mat = new int[200][200];
public static void main(String[] args) throws IOException {
// 把输入 load 进来,保存在内存里
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 一个一个读数字(速度快)
StreamTokenizer in = new StreamTokenizer(br);
// 输出缓冲区(集中输出更快)
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
// 文件没有结束就继续(支持多组输入)
while (in.nextToken() != StreamTokenizer.TT_EOF) {
// n:二维数组的行
int n = (int) in.nval;
in.nextToken();
// m:二维数组的列
int m = (int) in.nval;
// 读矩阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
in.nextToken();
mat[i][j] = (int) in.nval;
}
}
// 输出矩阵(示例:直接打印)
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.print(mat[i][j]);
// 如果需要空格分隔,可改成:out.print(mat[i][j] + " ");
}
out.println();
}
}
out.flush();
out.close();
br.close();
}
}

2. 按行读:用 readLine() 读取整行#

有时候的题目输入是一行一行的,但是题目却不告诉你每行的长度,这时候就比较操蛋了,需要按行读完数据自己处理

示例#

输入若干行,每行都是一串整数,输出每行的和。

import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
String line;
while ((line = in.readLine()) != null) {
// 防止空行导致 split 出现问题(可选)
line = line.trim();
if (line.isEmpty()) continue;
String[] parts = line.split(" ");
int sum = 0;
for (String num : parts) {
sum += Integer.parseInt(num);
}
out.println(sum);
}
out.flush();
in.close();
out.close();
}
}
【算法笔记】(三)处理输入和输出
http://hgqwd.icu/posts/suanfa3/
作者
天线宝宝死于谋杀
发布于
2026-01-09
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

封面
Sample Song
Sample Artist
封面
Sample Song
Sample Artist
0:00 / 0:00