Time Limit: 1 secs, Memory Limit: 32 MB
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.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.
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.
1 01 11 13 11 32 21 22 10 88
0 1INVALID1 2INVALID
题目分析
求森林最大宽度与深度
拓扑排序,若存在环则失败
每轮确定入度为零的节点数即为该层的宽度
轮数即为深度
一直WA是忽略了题目还限制了不存在两条边指向一个节点,即每个点的入度必须<=1
#include <iostream> #include <vector> #include <memory.h> struct Node { int indegree; std::vector<int> child; }; int main() { int num, edge; while (std::cin >> num >> edge && num != 0) { Node nodes[num+1]; for (int i = 1; i <= num; ++i) { nodes[i].indegree = 0; } bool visited[num+1]; memset(visited, false, sizeof(visited)); bool valid = true; int papa, son; for (int i = 0; i < edge; ++i) { std::cin >> papa >> son; nodes[son].indegree++; nodes[papa].child.push_back(son); if (nodes[son].indegree == 2) valid = false; } if (!valid) { std::cout << "INVALID" << std::endl; continue; } int height = -1; int width = 0; int count = 0; while (true) { std::vector<int> root; for (int i = 1; i <= num; ++i) { if (!visited[i] && nodes[i].indegree == 0) { root.push_back(i); } } if (root.size() == 0) break; width = width < root.size() ? root.size() : width; for (int i = 0; i < root.size(); ++i) { visited[root[i]] = true; count++; for (int j = 0; j < nodes[root[i]].child.size(); ++j) nodes[nodes[root[i]].child[j]].indegree--; } height++; } if (count == num) std::cout << height << " " << width << std::endl; else std::cout << "INVALID" << std::endl; } }