Rerouting Rapids

시간 제한1초메모리 제한2048 MB

요약
숲 구조에서 일부 간선을 조상 쪽으로 옮길 수 있을 때, 한 정점으로 들어오는 최대 간선 수를 최소화한다.
난이도

어려움10점 중 8점

유형
트리, 이분 탐색, 그리디, DFS
정답자
아직 제출이 없습니다

문제

The famous East Manitoba river that flows through Edmonton consists of NN rapids. The river is a popular rafting destination, with many visitors coming to the river each summer. When a visitor enters a rapid ii, the current will take them to some unique other rapid p_ip\_i, except when ii is the end of the river. Because water can only flow downhill, visitors can never flow back into the rapid at which they started. It is often the case that multiple rapids jj, j′j' flow into the same rapid p_j=p_j′p\_j=p\_{j'}.

Unfortunately, there have been many collisions lately in rapids that have many other rapids feeding into them, as many visitors may enter the same rapid at similar times, each being fed into it by a different rapid. You work for the City of Edmonton and have been tasked with rerouting some rapids to decrease the rate of collisions. If it’s possible for a visitor to start at some rapid ii and eventually reach another rapid jj, you may shortcut rapid ii to lead directly into rapid jj, setting p_i=jp\_i=j.

You wish to reroute rapids in this manner to minimize the maximum number of rapids feeding into any given rapid. Report this minimum number.

Figure 1: Illustration of the second sample case. By rerouting rapid 33 to lead directly to rapid 11, all rapids now have at most two rapids feeding into them.

입력

The first line of input contains one integer NN, the number of rapids in the river (1≤N≤1051≤N≤10^5). The second line contains NN integers p_1,p_2,…,p_np\_1,p\_2,\dots ,p\_n (0≤p_i≤N0≤p\_i≤N). If 1≤p_i≤N1≤p\_i≤N, then p_ip\_i is the rapid that the iith rapid feeds into. Otherwise, if p_i=0p\_i=0, then the iith rapid is at the end of the river. It is guaranteed that p_i=0p\_i=0 for exactly one of the indices 1≤i≤N1≤i≤N, and there is no way to start at the iith rapid and eventually return to it for any ii.

출력

Output the minimum possible highest number of rapids feeding into any given rapid, subject to rerouting as described above.

예제2

  1. 예제 1

    입력
    5
    2 0 2 2 2
    
    예상 출력
    4
    
  2. 예제 2

    입력
    5
    0 1 2 2 2
    
    예상 출력
    2