0

My code exceeds the time limit at test case 23. I have used dfs to traverse the connected houses. I did everything I could to optimize from my side. Kattis problem: where's my internet?

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);
            }
        }
    }
}
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

1 Answers1

1

The problem is not in your algorithm. It is just that input and output in Java is too slow for this online judge.

The solution is to use more efficient input and output code:

  • For input, use a custom Fast Scanner. See this page for several options.
  • For output, write the result in a StringBuilder, and then output this StringBuilder with a single System.out.

I was able to pass all the tests on your problem just by applying these two optimisations.

obourgain
  • 8,856
  • 6
  • 42
  • 57
  • `dfs()` takes most of the time and there is no input/output. – Cyril Nov 12 '21 at 14:43
  • @Cyril My experience with online judge is that `Scanner` is too slow to handle 200 000 lines of input. In my test, changing to a fast scanner change the exec time from >1s (which fails) to .59s (which pass). The algorithm is O(n), I don't think it is the issue. – obourgain Nov 12 '21 at 14:53