program name
    implicit none
    integer(4):: n,i,cnt
    integer(4),allocatable:: a(:)
    logical,allocatable:: pulled(:)

    read*, n
    allocate(a(n),pulled(n))

    do i=1,n
        read*, a(i)
    end do

    pulled(:) = .false.
    i=1
    cnt = 0
    do while(.not.(pulled(2)))
        i = a(i)
        if (pulled(i)) then
            print*, -1
            stop
        end if
        pulled(i) = .true.
        cnt=cnt+1
    end do

    print*, cnt

end program name