繁体   English   中英

我的代码超过了时间限制。 如何使我的代码更加优化?

[英]My code exceeds the time limit. How can I make my code more optimized?

我的代码超过了测试用例23的时间限制。我已经使用dfs遍历了连接的房屋。 我尽我所能从我这边优化。 凯蒂斯,问题:我的互联网在哪里? https://open.kattis.com/problems/wheresmyinternet

import java.util.Scanner;
import java.util.HashMap;
import java.util.ArrayList;

class Main{
    static boolean[] isVisited;
    static HashMap<Integer, ArrayList<Integer>> hashHouses;

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

        int numberOfHouses = scanner.nextInt();
        int numberOfCables = scanner.nextInt();

        hashHouses = new HashMap<>();

        for (int i = 1; i < numberOfHouses + 1; i++){
            hashHouses.put(i, new ArrayList<Integer>());
        }

        for (int i = 0; i < numberOfCables; i++){
            int x = scanner.nextInt();
            int y = scanner.nextInt();

            hashHouses.get(x).add(y);
            hashHouses.get(y).add(x);
        }

        isVisited = new boolean[numberOfHouses + 1];
        isVisited[1] = true;

        dfs(1);

        boolean isConnected = true;
        for (int i = 1; i < numberOfHouses + 1; i++){
            if (!isVisited[i]){
                System.out.println(i);
                isConnected = false;
            }
        }

        if (isConnected) System.out.println("Connected");
    }

    static void dfs(int start) {
        isVisited[start] = true;
        for (Integer i : hashHouses.get(start)) {
            if (!isVisited[i]) {
                dfs(i);
            }
        }
    }
}

问题不在于你的算法。 只是Java中的输入输出太慢了,这个在线判断。

解决方案是使用更高效的输入和输出代码:

  • 对于输入,请使用自定义快速扫描仪。 有关多个选项,请参阅页面。
  • 对于输出,将结果写入 StringBuilder,然后使用单个System.out输出此 StringBuilder。

通过应用这两个优化,我能够通过对您的问题的所有测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM