Sicily 1034 Forest(DFS)

//图的遍历,DFS,统计森林的宽度和深度,加上对环的判断 //一道这么简单的题我一开始用BFS,结果WA到吐血,唉,我这个大水人 #include<iostream> #include<vector> #include<cstring> using namespace std; bool vis[105],ok; int width[105]; vector<int> E[105];//邻接表 int N,M,W,D,in[105]; void dfs(int u,int d) { if(vis[u])//发现已搜过的点,证明存在环 { ok = 0; return; } vis[u] = 1; if(d > D) D = d;//记录深度 width[d]++;//记录当前深度的结点个数,也就是宽度 if(width[d] > W) W = width[d]; for(int i = 0;i < E[u].size();++i) { if(!ok) return; int v = E[u][i]; dfs(v,d+1); } } int main() { int u,v; while(scanf("%d%d",&N,&M) && N) { ok = 1; D = W = 0; if(M >= N) ok = 0; memset(E,0,sizeof(E)); memset(in,0,sizeof(in)); memset(width,0,sizeof(width)); memset(vis,0,sizeof(vis)); for(int i = 0;i < M;++i) { scanf("%d%d",&u,&v); E[u].push_back(v); in[v]++; } for(int i = 1;i <= N;++i) { if(in[i] == 0)//对入度为0的点进行深搜 dfs(i,0); } for(int i = 1;i <= N;++i) if(!vis[i]) ok = 0;//如果搜索完还有点未遍历过,证明存在环 if(!ok) printf("INVALID/n"); else printf("%d %d/n",D,W); } return 0; }  

你可能感兴趣的:(Sicily 1034 Forest(DFS))