program moving_piece
  implicit none
  integer :: n, k, p(5000) = 0, i, j, m, h, q, r
  integer(8) :: c(5000) = 0, x = -6e18, w, s
  read(*,*) n, k
  read(*,*) p(1:n)
  read(*,*) c(1:n)
  do i = 1, n
    m = i
    h = 1
    s = c(m)
    x = max(x, s)
    do while (h < k .and. p(m) /= i)
      m = p(m)
      h = h + 1
      s = s + c(m)
      x = max(x, s)
    end do
    if (h == k .or. s < 0) cycle
    q = k / h
    r = mod(k, h)
    m = i
    w = 0
    do j = 1, h
      w = w + c(m)
      x = max(x, s * merge(q - 1, q, j > r) + w)
      m = p(m)
    end do
  end do
  write(*,'(i0)') x
end program moving_piece