Codeforces 427E:用Java编写足够快的解决方案是不可能的

时间:2014-05-05 12:31:40

标签: java

我确信这里有很多人对Codeforce问题感兴趣,所以问题在这里:

问题:我坚持解决one of Codeforces problems。我在第21次测试中得到Time limit exceeded。我发现solition但它似乎比我的慢。

经过一段时间的考虑,我认为在Java 7中编写更快的解决方案是不可能的。

问题:是否可以在Java 7中编写更快的解决方案?

我的解决方案:

public class PolicePatrol {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);

        int criminalAmount = in.nextInt();
        int patrolCarCapacity = in.nextInt();
        int[] criminalLocations = new int[criminalAmount];
        for (int i = 0; i < criminalLocations.length; i++)
            criminalLocations[i] = in.nextInt();

        long distance = calcDistance(criminalLocations, patrolCarCapacity);
        out.print(distance);
        out.flush();
    }

    protected static long calcDistance(int[] criminals, int patrolCapacity) {
        // put patrol on the position of the middle criminal
        int patrolPosition = criminals[criminals.length / 2]; 

        double itr = (criminals.length - 1) / 2.0;
        // number of travels to the left from the police station
        int itrLeft = (int) Math.ceil(Math.ceil(itr) / ((double) patrolCapacity)); 
        //number of travels to the right from the police station
        int itrRight = (int) Math.ceil(Math.floor(itr) / ((double) patrolCapacity)); 

        long distance = 0;

        int lo = 0;
        while (itrLeft-- > 0) {
            distance += patrolPosition - criminals[lo];
            lo = lo + patrolCapacity;
        }

        int hi = criminals.length - 1;
        while (itrRight-- > 0) {
            distance += criminals[hi] - patrolPosition;
            hi -= patrolCapacity;
        }
        return 2 * distance;
    }
}

更新:如果您对解决Codeforce问题不感兴趣,请定义最简单的任务。

Input:
arraySize
step
array

Output:
Number that represents summary of all Math.abs(array[array.length / 2] - array[i]) for all `i % step == 0`

1 个答案:

答案 0 :(得分:3)

Scanner is notoriously slow。在用更快的实现替换它之后我得到了accepted with your code。代码取自IFMO training Java template

static class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    FastScanner(InputStream f) {
        br = new BufferedReader(new InputStreamReader(f));
    }

    String next() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            st = new StringTokenizer(br.readLine());
        }
        return st.nextToken();
    }

    int nextInt() throws IOException {
        return Integer.parseInt(next());
    }
}

对于输入中的1M整数,这会将输入解析所需的时间从我的机器上的~1.3s减少到~0.35s,这是4倍的改进。