# frozen_string_literal: true

n, k = gets.split.map(&:to_i)
p = gets.split.map(&:to_i).unshift(0)
c = gets.split.map(&:to_i).unshift(0)
d = []
(1..n).each do |i|
  g = {}
  ni = i
  loop do
    break if g[ni] || d.select { |e| e[ni] }.size.positive?

    g[ni] = true
    ni = p[ni]
  end
  d.push g.dup if g.size.positive?
end

cs = []
d.each do |dg|
  css = []
  dg.each_key do |i|
    css.push c[i]
  end
  cs.push css
end

def findmax(ary, k)
  k %= ary.size
  k = ary.size if k.zero?
  max = -1 * 10**14
  a = ary + ary[0..(k - 1)]
  (0..(ary.size - 1)).each do |i|
    s = 0
    (0..(k - 1)).each do |j|
      s += a[i + j]
      max = s if max < s
    end
  end
  max
end
m = []
cs.each do |cc|
  if cc.sum <= 0
    m.push findmax(cc, k)
  else
    m.push cc.sum * (k / cc.size) + findmax(cc, k)
  end
end
puts m.max
