1034. Forest
Time Limit: 1sec Memory Limit:32MB
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
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
/运用深搜比较经典的一道题,注意要把每一次搜下去的宽度值修改,用一个widtys数组保存每一层的宽度值,用一个vector保存邻接表,用visit数组标志是否已经读过某节点,可以判断是否出现了回路,用into数组判断是否已经有入边,可以在输入时就把非forest的情况分析出来,省略不必要的计算。
#include <stdio.h>
#include <memory.h>
#include <vector>
using namespace std;
#define MAX 105
vector<int> vec[MAX];
int widths[MAX];
bool visit[MAX], isforest, into[MAX];
int n, m, depth, width;
void dfs(int i,int d)
{
if(visit[i]==1)
{
isforest = 0;
return;
}
visit[i]=1;
if (d>depth)
depth=d;
widths[d]++;
if (widths[d] > width)
width = widths[d];
for (int j=0; j< vec[i].size(); j++)
dfs(vec[i][j], d+1);
}
int main()
{
int i,temp1,temp2;
while(scanf("%d%d", &n, &m)!=EOF&&n!=0)
{
memset(into,0,sizeof(into));
memset(visit,0,sizeof(visit));
memset(widths,0,sizeof(widths));
memset(vec,0,sizeof(vec));
depth=0,width=0;
isforest=1;
while(m--)
{
scanf("%d%d", &temp1, &temp2);
vec[temp1].push_back(temp2);
if (into[temp2]==1||temp1==temp2)
isforest=0;
else into[temp2]=1;
}
if (isforest==0)
{
printf("INVALID\n");
continue;
}
for (i=1;i<=n;i++)
if(into[i]==0)
dfs(i,0);
for (i=1;i<=n;i++)
{
if(visit[i]==0)
{
isforest=0;
break;
}
}
if (isforest==0)
printf("INVALID\n");
else
printf("%d %d\n", depth, width);
}
return 0;
}