program sample
    implicit none
    character(100)::s
    integer(8) :: i,j,n,a,b,c,d,ma,k,l
    integer(8),allocatable :: x(:),y(:),z1(:),z2(:),m(:)
  
    read(*,*) n,k
    allocate(x(n),y(n),z1(n),z2(n),m(n))
    read(*,*)x
    read(*,*)y
    if(k==1)then
        write(*,*)maxval(y)
        stop
    end if

    do i=1,n
        m(:)=-10**9
        
        a=i
        a=x(a)
        m(1)=y(a)
        do j=2,k
            a=x(a)
            m(j)=m(j-1)+y(a)
            if(j==k)then
                z1(i)=maxval(m)
                exit
            elseif(a==i)then
                if(m(j)>0)then
                    b=(k/j-1)*m(j)+maxval(m)
                    d=mod(k,j)
                    ma=-10**9
                    do l=1,d
                        if(m(l)>ma)then
                            ma=m(l)
                        end if
                    end do
                    c=(k/j)*m(j)+ma
                    z1(i)=max(b,c)
                else
                    z1(i)=maxval(m)
                endif
                exit
            end if
        end do
    end do
    write(*,*)maxval(z1)

    stop
end program sample
  

