This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <stdio.h>
#include <stdlib.h>
#define N	20000
int max(int a, int b) { return a > b ? a : b; }
int *ej[N], eo[N];
void append(int i, int j) {
	int o = eo[i]++;
	if (o >= 2 && (o & o - 1) == 0)
		ej[i] = (int *) realloc(ej[i], o * 2 * sizeof *ej[i]);
	ej[i][o] = j;
}
int dd[N];
void dfs1(int i, int d) {
	int o;
	dd[i] = d;
	for (o = eo[i]; o--; ) {
		int j = ej[i][o];
		dfs1(j, d + 1);
	}
}
int d_;
void dfs2(int i, int d) {
	int o;
	d_ = max(d_, d);
	for (o = eo[i]; o--; ) {
		int j = ej[i][o];
		dfs2(j, d + 1);
	}
}
int main() {
	static int pp[N], qu[N];
	static char visited[N];
	int n, cnt, h, i, j, o;
	scanf("%d", &n);
	for (i = 0; i < n; i++)
		ej[i] = (int *) malloc(2 * sizeof *ej[i]);
	for (i = 0; i < n; i++) {
		scanf("%d", &pp[i]);
		if (pp[i] != -1)
			append(pp[i], i);
	}
	for (i = 0; i < n; i++)
		if (pp[i] == -1)
			dfs1(i, 1);
	i = 0, cnt = 0;
	while (i >= 0 && !visited[i])
		qu[cnt++] = i, visited[i] = 1, i = pp[i];
	if (i >= 0) {
		d_ = 0;
		for (i = 0; i < n; i++)
			d_ = max(d_, dd[i]);
		printf("%d\n", cnt + d_);
	} else {
		d_ = cnt;
		for (i = 0; i < n; i++)
			if (pp[i] == -1 && i != qu[cnt - 1])
				dfs2(i, cnt + 1);
		for (h = cnt - 1; h > 0; h--) {
			i = qu[h];
			for (o = eo[i]; o--; ) {
				j = ej[i][o];
				if (j != qu[h - 1])
					dfs2(j, cnt + 1);
			}
		}
		printf("%d\n", d_);
	}
	return 0;
}
Compilation message (stderr)
forensic.c: In function 'append':
forensic.c:13:23: warning: suggest parentheses around '-' in operand of '&' [-Wparentheses]
   13 |  if (o >= 2 && (o & o - 1) == 0)
      |                     ~~^~~
forensic.c: In function 'main':
forensic.c:49:2: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
   49 |  scanf("%d", &n);
      |  ^~~~~~~~~~~~~~~
forensic.c:53:3: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
   53 |   scanf("%d", &pp[i]);
      |   ^~~~~~~~~~~~~~~~~~~| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |