Algorithm 在解决SPOJ PT07Y时获得TLE

Algorithm 在解决SPOJ PT07Y时获得TLE,algorithm,graph,tree,microsoft-distributed-file-system,Algorithm,Graph,Tree,Microsoft Distributed File System,是问题的链接 它说给定的边可以找到图是否是树 我正在检查边的数量是否比节点的数量少一个,以及图中是否存在循环 为了检查图中是否有循环,我将节点标记为已访问,并且如果我再次面对同一个节点,并且它不是父节点。我推断它有一个循环 我是这样做的。它给我带来了快乐。我不知道我要做什么优化 class Main{ public static PrintWriter out; public static boolean isTree(int node,HashSet<Integer>

是问题的链接

它说给定的边可以找到图是否是树

我正在检查边的数量是否比节点的数量少一个,以及图中是否存在循环

为了检查图中是否有循环,我将节点标记为已访问,并且如果我再次面对同一个节点,并且它不是父节点。我推断它有一个循环

我是这样做的。它给我带来了快乐。我不知道我要做什么优化

class Main{
    public static PrintWriter out;
    public static boolean isTree(int node,HashSet<Integer> hs,HashMap<Integer,LinkedList<Integer>> graph, int parent){

        hs.add(node);
        LinkedList<Integer> children = graph.get(node);
        Iterator<Integer> it = children.iterator();
        boolean op = true;

        while(it.hasNext()){

            int child = it.next();

            if(child!=parent && (hs.contains(child) || !isTree(child,hs,graph,node)))
                return false;
        }

        return op;
    }

    public static void main(String[] args) {
        HashMap<Integer,LinkedList<Integer>> graph = new HashMap<>();
        MScan scan = new MScan();
        int nodes = scan.nextInt();
        for(int i=0; i<nodes; i++){
            graph.put(i+1, new LinkedList<Integer>());
        }
        int edge = scan.nextInt();
        if(nodes-edge!=1){
            out = new PrintWriter(new BufferedOutputStream(System.out), true);
            out.println("NO");
            out.close();
        }
        else{
            for(int i=0; i < edge; i++){
                int first = scan.nextInt();
                int second = scan.nextInt();
                graph.get(first).add(second);
                graph.get(second).add(first);
            }
            out = new PrintWriter(new BufferedOutputStream(System.out), true);
            out.println((nodes-edge==1)?isTree(1,new HashSet<Integer>(),graph,-1)?"YES":"NO":"NO");



            out.close();
        }
    }
}
主类{
公共静态打印输出;
公共静态布尔isTree(int节点、HashSet hs、HashMap图、int父节点){
hs.add(节点);
LinkedList子项=graph.get(节点);
Iterator it=children.Iterator();
布尔运算=真;
while(it.hasNext()){
int child=it.next();
if(child!=parent&(hs.contains(child)| |!isTree(child,hs,graph,node)))
返回false;
}
返回op;
}
公共静态void main(字符串[]args){
HashMap graph=新的HashMap();
MScan扫描=新MScan();
int nodes=scan.nextInt();

对于(int i=0;i为什么要使用hashset?这里没有必要这样做。存储和检索数据需要时间。它就像一个最小堆数据结构(输入数据时需要时间进行重塑)

因此,请改用普通布尔数组。
我的C++解决方案可能会帮助你更有效地执行< /P>

有N条边的树有N+1个顶点。确保这一点,请测试连接性。@user58697是的,我在最后一条语句中做了。我没有看到连接性测试。可能用较轻的布尔数组替换哈希集(指示每个节点是否已到达)会有帮助吗?另外,I/O可能需要大量时间。MScan是如何实现的?@qwertyman MScan使用BufferedReader。我将尝试使用布尔数组。我担心isTree是否会进入无限循环。我是否建议不要用重复的问题来回答?如果答案不依赖外部循环,则被认为更有价值,并且是未来的证明网站传达信息。请直接在这里提供核心答案。