program MovingPiece

    implicit none

    integer(16) :: N, K
    integer(16), allocatable :: P(:), C(:)
    integer(16) :: i, j, l
    integer(16) :: maxscore, temp

    read(*, *) N, K
    allocate(P(1:N), C(1:N))
    read(*, *) P
    read(*, *) C


    maxscore = -1000000000
    do i = 1, N
        l = P(i)
        temp = 0
        do j = 1, K
            temp = temp + C(l)
            if (maxscore < temp) then
                maxscore = temp
            end if
            l = P(l)
        end do
    end do

    write(*, *) maxscore

end program MovingPiece
