All problems

Problem 944

Maximum Employees to Be Invited to a Meeting

Hard · 30 pts · Graph, Topological Sort, Depth-First Search

Problem

N employees sit at a round table, and each will attend only if they sit next to their favourite person FAV[i] (never themselves). Find the largest number of employees you can invite. The favourites form a functional graph. One option is a single cycle of length 3 or more seated in order. The other is any number of mutual pairs (cycles of length 2), each extended by the longest chain of people leading into either member; all such extended pairs can sit together.

Input

The first line contains N. The second line contains FAV[0..N-1].

Output

Print the maximum number of employees who can be invited.

Constraints

2 <= N <= 100000; 0 <= FAV[i] < N; FAV[i] != i

Example input

4
2 2 1 2

Example output

3

Explanation

With FAV = 2 2 1 2, employees 1 and 2 like each other; employees 0 and 3 both like 2 but only one of them can sit beside 2 alongside 1. So at most 3 employees can be invited.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Find All Possible Recipes from Given Supplies Next: Longest Cycle in a Graph