Forest
|
Description
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. 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 . 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.Input
There’re several test cases. For each case, in the first line there are two integer numbers n and m (1≤n≤100, 0≤m≤100, m≤n*n) indicating the number of nodes and edges respectively , then m lines followed , for each line of these m lines there are two integer numbers a and b (1≤a,b≤n)indicating there’s an edge pointing from a to b. Nodes are represented by numbers between 1 and n .n=0 indicates end of input.
Output
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. Sample Input
Copy sample input to clipboard
1 0 1 1 1 1 3 1 1 3 2 2 1 2 2 1 0 88 Sample Output
0 1 INVALID 1 2 INVALID |
|
View Code
1 #include <iostream> 2 #include <vector> 3 #include <cstring> 4 using namespace std; 5 6 #define Max 102 7 vector<int>v[Max]; 8 int allWidth[Max]; 9 bool visited[Max]; 10 bool end[Max]; 11 bool forest; 12 int n, m; 13 int depth, width; 14 void dfs(int a, int d) 15 { 16 if (!forest) 17 return; 18 visited[a] = true; 19 if (depth < d) 20 depth = d; 21 if (width < ++allWidth[d]) 22 width = allWidth[d]; 23 int size = v[a].size(); 24 for (int i = 0; i < size; i++){ 25 if (visited[v[a][i]]){ 26 forest = false; 27 return; 28 }else{ 29 visited[v[a][i]] = true; 30 dfs(v[a][i], d+1); 31 } 32 } 33 } 34 35 int main() 36 { 37 int a, b; 38 while (cin >> n >> m && n){ 39 for (int i = 1; i <= n; i++) 40 v[i].clear(); 41 memset(visited, false, sizeof(visited)); 42 memset(end, false, sizeof(end)); 43 memset(allWidth, 0, sizeof(allWidth)); 44 depth = 0; 45 width = 0; 46 forest = true; 47 48 for (int i = 0; i < m; i++){ 49 cin >> a >> b; 50 v[a].push_back(b); 51 if (end[b] || a == b) 52 forest = false; 53 else 54 end[b] = true; 55 } 56 if (!forest){ 57 cout << "INVALID" << endl; 58 continue; 59 } 60 for (int i = 1; i <= n; i++){ 61 if (!end[i]){ 62 dfs(i, 0); 63 } 64 } 65 for (int i = 1; i <= n; i++){ 66 if (!visited[i]){ 67 forest = false; 68 break; 69 } 70 } 71 if (forest) 72 cout << depth << " " << width << endl; 73 else 74 cout << "INVALID" << endl; 75 } 76 77 //system("PAUSE"); 78 return 0; 79 }


浙公网安备 33010602011771号