In the field of computer science, forest is important and deeply researched , it is a model for many data structures . Now it’s your job here to calculate the depth and width of given forests. node
Precisely, a forest here is a directed graph with neither loop nor two edges pointing to the same node. Nodes with no edge pointing to are roots, we define that roots are at level 0 . If there’s an edge points from node A to node B , then node B is called a child of node A , and we define that B is at level (k+1) if and only if A is at level k . ios
We define the depth of a forest is the maximum level number of all the nodes , the width of a forest is the maximum number of nodes at the same level.For each case output one line of answer , if it’s not a forest , i.e. there’s at least one loop or two edges pointing to the same node, output 「INVALID」(without quotation mark), otherwise output the depth and width of the forest, separated by a white space. oop
1 0 1 1 1 1 3 1 1 3 2 2 1 2 2 1 0 88
0 1 INVALID 1 2 INVALID
本題要求森林的深度和寬度,建議用深搜,由於廣搜的循環控制條件很難寫,極易出錯或者死循環。要注意圖生成的森林中,可能會出現公共子節點以及環等不合法狀況,要注意判斷條件。DFS過程當中遇到了已經訪問過的節點說明有公共子節點的存在,DFS完成後仍有節點未被訪問說明有環存在。另外,一次完整的DFS過程當中求得的廣度只是一棵樹的廣度,要對同一深度的節點所有統計才能獲得森林的廣度。 spa
// Problem#: 1034 // Submission#: 1795986 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ // All Copyright reserved by Informatic Lab of Sun Yat-sen University #include <iostream> #include <cstring> using namespace std; #define N 101 #define M 101 bool flag; bool buffer[N][N]; bool visit[N]; bool isroot[N]; int maxd,n,m,maxb; int b[N]; void dfs( int p, int td ){ if( visit[p] ){ flag = false; return ; } visit[p] = true; maxd = td>maxd ? td : maxd; if(++b[td]>maxb) maxb = b[td]; for( int i=1 ; i<=n ; i++ ){ if( buffer[p][i] ){ if(!flag) return ; dfs(i,td+1); }else continue; } } int main(){ int x,y; while( cin>>n>>m && n ){ memset(buffer,0,sizeof(buffer)); memset(visit,0,sizeof(visit)); memset(isroot,true,sizeof(isroot)); flag = true; if(m>=n) flag = false; for( int i=0 ; i<m ; i++ ){ cin >> x >> y; buffer[x][y] = true; isroot[y] = false; } maxd = maxb = 0; memset(b,0,sizeof(b)); for( int i=1 ; i<=n ; i++ ) if( isroot[i] ) dfs(i,0); for( int i=1 ; i<=n ; i++ ){ if( !visit[i] ){ flag = false; break; } } if( flag ) cout << maxd << " " << maxb; else cout << "INVALID"; cout << endl; } return 0; }