A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
Employee A is the immediate manager of employee B
Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees.
The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
input
5
-1
1
2
1
-1
output
3
输入n个员工,编号从1到n。接着是n行,分别为这n个员工的直系经理的编号,如果为-1,则说明此员工没有直系经理。
用树的图形来解此题,求树的最高层数。因为我们输入的是每个成员的上司编号,即父节点的编号,所以只需从叶子节点开始向上搜,求出最大的层数即可。
代码实现:
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<cmath>
#include<algorithm>
#include<string>
#include<string.h>
using namespace std;
int father[2010];
int main() {
int n;
while (scanf("%d", &n) != EOF) {
for (int i = 1; i <= n; i++)
scanf("%d", &father[i]); //输入经理的编号
int ans;
int cnt = 0;
for (int i = 1; i <= n; i++) {
ans = 0; //记录树的深度
for (int j = i; j <= n; j = father[j]) { //j=father[j]用于判断是否已到根节点,如果到了根节
//点,则循环结束,此时的ans就是深度。
if (j != -1)
ans++;
else
break;
}
cnt = max(cnt, ans); //更新数据,找到最大的那个值即是答案
}
printf("%d\n", cnt);
}
return 0;
}
公司员工分为无上级和有上级两类,组织聚会时要求同一组内不存在上下级关系。给定每个员工的直接上级,求最少需要分成多少个组。输入包括员工数量及每个员工的直接上级,保证无循环管理。通过构建树形结构,自底向上计算最大深度,输出结果。
347

被折叠的 条评论
为什么被折叠?



