Home 算法笔试中处理输入和输出
Post
Cancel

算法笔试中处理输入和输出

目标

· 两种常用 I/O 模板:

  1. 数字流(StreamTokenizer) —— 适合大量数字、矩阵、直到 EOF 的多组数据
  2. 按行读取(BufferedReader + StringTokenizer) —— 适合“每行一个用例/表达式”的题

· 建议:

  • 尽量用 BufferedReader / StreamTokenizer / PrintWriter,避免 ScannerSystem.out(较慢)
  • 输出尽量用 StringBuilder + PrintWriter,只在最后一次性打印
  • 需要频繁读写的大型结构,可用全局静态数组减少临时分配(避免反复 new),但仍计入内存限制(只是避免栈溢出和频繁 GC)
  • 不推荐:临时动态空间
  • 推荐:全局静态空间
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//全局静态空间,不会被卡内存限制
    public static int MAXN = 201;
    public static int MAXM = 201;
    public static int[][] mat = new int[MAXN][MAXM];
    public static int[] arr = new int[MAXM];

    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;
            //装数字的矩阵,临时动态生成
            int[][] mat = new int[n][m];
            for(int i = 0; i<n;i++){
                for(int j = 0; j<m ;j++){
                    in.nextToken();
                    mat[i][j]=(int)in.nval;//临时动态空间
                }
            }
            out.println(maxSumSubmatrix(mat,n,m));
        }
        out.flush();
        out.close();
    }


    public static void main(String[] args) throws IOException{
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        while((line = in.readLine()) != null){
            parts = line.split(""); //根据空格切分
            sum = 0; //求累加和
            for(String num : parts){
                sum+=Integer.valueOf(num); //把每一个数字都转成整形
            }
            out.println(sum);
        }
        out.flush();
        in.close();
        out.close();
    }
This post is licensed under CC BY 4.0 by the author.