1. 程式人生 > 實用技巧 >ACM使用Java提交總是超時的解決方法

ACM使用Java提交總是超時的解決方法

轉載自作者:日沉雲起
連結:https://blog.csdn.net/richenyunqi/article/details/84350768
來源:CSDN

當你發現程式碼相同,c++ 和 Java分別提交,c++通過了而Java卻沒有,那就是因為以下三種情況了:

1、不能使用Scanner輸入

  • 用BufferReader類和StringTokenizer類代替Scanner類來讀取輸入,讀取輸入的語法如下:
class Reader {
    static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    
static StringTokenizer tokenizer = new StringTokenizer(""); static String nextLine() throws IOException{// 讀取下一行字串 return reader.readLine(); } static String next() throws IOException {// 讀取下一個字串 while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); }
return tokenizer.nextToken(); } static int nextInt() throws IOException {// 讀取下一個int型數值 return Integer.parseInt(next()); } static double nextDouble() throws IOException {// 讀取下一個double型數值 return Double.parseDouble(next()); } }

舉例

poj(北京大學程式線上評測系統)的第2479DP題,使用Scanner總是超時,換成上面的方式直接AC。程式碼:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class P2479_MaximumSum {
    public static void main(String[] args) throws IOException {
        int t = Reader.nextInt();
        int sum, i;
        for (i = 0; i < t; i++) {
            int n = Reader.nextInt();
            int[] arr = new int[n];
            for (i = 0; i < n; i++) {
                arr[i] = Reader.nextInt();
            }
            int[] larr = new int[n];
            int[] rarr = new int[n];
            larr[0] = arr[0];
            rarr[n - 1] = arr[n - 1];
            for (i = 1, sum = arr[0]; i < n - 1; i++) {
                sum = Math.max(sum + arr[i], arr[i]);
                larr[i] = Math.max(sum, larr[i - 1]);
            }
            int max = rarr[n - 1] + larr[n - 2];
            for (i = n - 2, sum = arr[n - 1]; i > 0; i--) {
                sum = Math.max(sum + arr[i], arr[i]);
                rarr[i] = Math.max(sum, rarr[i + 1]);
                max = Math.max(rarr[i] + larr[i - 1], max);
            }
            System.out.println(max);
            if (i != 0) System.out.println();   // 題目要求每個案例後都有一個空行,注意ps:只有一個案例時,不需要空行
        }
    }
}
class Reader {
    static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer tokenizer = new StringTokenizer("");
    static String nextLine() throws IOException {// 讀取下一行字串
        return reader.readLine();
    }
    static String next() throws IOException {// 讀取下一個字串
        while (!tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(reader.readLine());
        }
        return tokenizer.nextToken();
    }

    static int nextInt() throws IOException {// 讀取下一個int型數值
        return Integer.parseInt(next());
    }

    static double nextDouble() throws IOException {// 讀取下一個double型數值
        return Double.parseDouble(next());
    }
}