ZJU PAT 1021 最后一个case过不去。该怎么处理

ZJU PAT 1021 最后一个case过不去。
1021. Deepest Root (25)

时间限制
1500 ms
内存限制
32000 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
A graph which is connected and acyclic can be considered a tree. The height of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=10000) which is the number of nodes, and hence the nodes are numbered from 1 to N. Then N-1 lines follow, each describes an edge by given the two adjacent nodes' numbers.

Output Specification:

For each test case, print each of the deepest roots in a line. If such a root is not unique, print them in increasing order of their numbers. In case that the given graph is not a tree, print "Error: K components" where K is the number of connected components in the graph.

Sample Input 1:
5
1 2
1 3
1 4
2 5
Sample Output 1:
3
4
5
Sample Input 2:
5
1 3
1 4
2 5
3 4
Sample Output 2:
Error: 2 components




题目里,N<=10000,这可能就是造成最后一个case   内存超限   的原因

以下是代码。。
#include <iostream>
#include <string.h>
using namespace std;
const int MAX=10002;
int N;
bool edges[MAX][MAX];
int root[MAX];
int level;
bool visited[MAX];
//广度优先搜索
int BFS(int v)
{
int check[MAX];
int l=0;
int level[MAX];
memset(level,0,sizeof(level));
memset(check,-1,sizeof(check));
visited[v]=1;
int queue[MAX];
int front=0,rear=0;
queue[rear++]=v;
level[v]=l;                //v结点的层数为l
check[v]=0;
while(front!=rear)
{
int v1=queue[front];
front=front%(MAX-1)+1;
l=level[v1]+1;        //v结点的子节点层数为 v结点所在层数+1
for(int i=1;i<=MAX;++i)
{
if(visited[i]==0&&edges[v1][i]==1)
{
if(check[i]!=-1)
{
return -1;
}
visited[i]=1;
check[i]=v1;
queue[rear]=i;
rear=rear%(MAX-1)+1;
level[i]=l;     //i结点的层数为l
}
}
}
return l;
}
int main()
{
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
scanf("%d",&N);
int a,b;
int q=1;
while(scanf("%d %d",&a,&b)!=EOF)
{
++q;
edges[a][b]=edges[b][a]=1;
}
int i=0;
for(i=1;i<=N;++i)
{
memset(visited,0,sizeof(visited));
int level;
level=BFS(i);
//////////////
int count=1;
int mark=0;
for(int h=1;h<=N;++h)
{ if(visited[h]==0)
{
mark=1;
++count;
BFS(h);
}
}
if(level==-1||mark==1)
{
printf("Error: %d components",count);
return 0;
}
////////////
root[i]=level;
}
int max=0;
for(int k=1;k<=N;++k)
{
if(root[k]>max)max=root[k];
}
for(int k=1;k<=N;++k)
{
if(root[k]==max)printf("%d\n",k);
}
return 0;
}
ZJU PAT 内存超限 1021

------解决方案--------------------
就算不是树,题目里也说了只有n-1条边。用不用bool存没关系。n^2还是n^2。本来只要几十k就能存下的东西你再怎么用bool都要100m。