I have written a JAVA program which hardly takes 3-4 MB of memory but still somehow exceeds the 16 MB memory limit on the grader in which I submit the problems for judging.
I have an Integer 2D Array of size 2500*100 which occupies around 1 MB ,and an adjacency list with a maximum of 2500 nodes and 2499 edges (Tree) .
Why does it exceed the 16 MB memory limit? I know JAVA has some overhead but I still can't understand why it exceeds the limit. It would be of great help to me if someone could explain the reason as to why the code consumes so much memory.I am also doing a DFS which will consume some stack memory but there is no reason for it to exceed the 16 MB Limit.
Here is the code:
import java.io.*;
import java.util.*;
class CateringContracts2pi
{
static ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(2505);
static int mod = 10243;
static int ans=0;
static int dp[][]=new int[2501][101];
static int temp[]=new int[101];
static int N,K;
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
for(int i=0;i<2505;i++)
adj.add(new ArrayList<Integer>());
N = sc.nextInt();
K = sc.nextInt();
for(int i=1;i<N;i++)
{
int u = sc.nextInt();
int v = sc.nextInt();
adj.get(u).add(v);
adj.get(v).add(u);
}
for(int i = 1; i <= N; i++)
{
dp[i][0] = dp[i][1] = 1;
}
dfs(1,0);
System.out.println(ans);
}
static void dfs(int node,int par)
{
int sz = adj.get(node).size();
for(int i=0;i<sz;i++)
{
int next = adj.get(node).get(i);
if(next==par)continue;
dfs(next,node);
Arrays.fill(temp,0);
for(int j=1;j<=K;j++)
{
for(int k=1;k+j<=K;k++)
{
temp[j+k]+=dp[node][j]*dp[next][k] % mod;
}
}
for(int j=1;j<=K;j++)
{
dp[node][j] += temp[j];
dp[node][j] %= mod;
}
}
ans+=dp[node][K];
ans%=mod;
}
}