[英]My code exceeds the time limit. How can I make my code more optimized?
My code exceeds the time limit at test case 23. I have used dfs to traverse the connected houses.我的代码超过了测试用例23的时间限制。我已经使用dfs遍历了连接的房屋。 I did everything I could to optimize from my side.我尽我所能从我这边优化。 Kattis, problem: where's my internet?凯蒂斯,问题:我的互联网在哪里? https://open.kattis.com/problems/wheresmyinternet 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);
}
}
}
}
The problem is not in your algorithm.问题不在于你的算法。 It is just that input and output in Java is too slow for this online judge.只是Java中的输入输出太慢了,这个在线判断。
The solution is to use more efficient input and output code:解决方案是使用更高效的输入和输出代码:
System.out
.对于输出,将结果写入 StringBuilder,然后使用单个System.out
输出此 StringBuilder。I was able to pass all the tests on your problem just by applying these two optimisations.通过应用这两个优化,我能够通过对您的问题的所有测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.