在DFS实现中获取StackOverflowError以获取非常大的输入

问题描述

使用Java在HackerEarth上练习DFS问题时,其中一个测试用例在签出时会导致NZEC错误,但显示 StackOverFlow错误。我检查了很多次,但是所有的测试用例都通过了,唯一的一个是导致错误,这不是针对特定的问题,而是针对许多问题(DFS问题),一个测试用例总是出现在10个或10个中。 20,使用Java求解时总是会导致NZEC。

我不是由于我的邻接表实现还是其他原因。这是问题之一。

问题https://www.hackerearth.com/practice/algorithms/graphs/depth-first-search/practice-problems/algorithm/feasible-relations/

我的代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.*;

public class TestClass {

    static long mod = 1000000007;
    static String[] temp;
    static  int[] node;
    static  int[] vis;
    public static final BufferedReader br = new BufferedReader(new InputStreamReader(system.in));

    public static void main (String[] args) throws IOException {

        int testCases= Integer.parseInt(br.readLine().split(" ")[0]);

        while (testCases > 0) {
            temp = br.readLine().split(" ");
            int N = Integer.parseInt(temp[0]);
            int K = Integer.parseInt(temp[1]);

            HashMap<Integer,ArrayList<Integer>> forEqual = new HashMap<>();
            ArrayList<int[]> edgeList = new ArrayList<>();

            for (int i = 0; i < K; i++) {
                temp = br.readLine().split(" ");
                int u = Integer.parseInt(temp[0]);
                int v = Integer.parseInt(temp[2]);
                if (temp[1].equals("=")) {
                    forEqual.computeIfAbsent(u,k -> new ArrayList<>()).add(v);
                    forEqual.computeIfAbsent(v,k -> new ArrayList<>()).add(u);
                } else {
                    edgeList.add(new int[]{u,v});
                }
            }

            boolean[] vis = new boolean[1000005];
            node = new int[1000005];
            int c = 0;
            for (int i : forEqual.keySet()) {
                if (!vis[i]) {
                    c++;
                    DFS(i,forEqual,c,vis);
                }
            }
            boolean flag = true;

            for(int[] i : edgeList){
                if(node[i[0]] == node[i[1]]){
                    flag = false;
                    break;
                }
            }
            System.out.println(flag ? "YES" : "NO");
            testCases--;
        }
    }

    private static void DFS(int i,HashMap<Integer,ArrayList<Integer>> forEqual,int c,boolean[] vis) {
        vis[i] = true;
        node[i] = c;
        for (int v : forEqual.get(i)) {
            if (!vis[v]) {
                DFS(v,vis);
            }
        }
    }

}

Error Log

解决方法

没有人回答我的问题,这个问题不是来自现场比赛,我花了一个星期的时间来解决我的问题。 StackOverFlow的问题是由于HackerEarth IDE和Java的类似在线IDE上的堆栈调用数量受到限制,仅允许进行100,000个调用,为避免这种情况,请创建线程对象并手动将堆栈大小作为参数传递,将增加堆栈大小。

class Solution{
     public static void main (String[] args) throws IOException {
          new Thread(null,new TestClass(),"",1 << 26).start();
     }
     public void run() {
         // DO WHATEVER YOU WANT 
     }
}