(N,K),P,C = $<.map{|ln| ln.split.map(&:to_i) }

V = [nil]*N
A = P.map{|p|
	p -= 1
	next if V[p]
	V[p] = true
	a = [C[p]]
	q = P[p]-1
	until q == p
		V[q] = true
		a << C[q]
		q = P[q]-1
	end
	next a
}.compact
Max = lambda{|a,k| k = a.size if a.size<k
	s = [0]
	a.each{|_| s << s[-1]+_ }
	a.lazy.take(k-1).each{|_| s << s[-1]+_ }
	[*0...s.size].product([*0...s.size]).map{|i,j|
		i<j && j<=i+k ? s[j]-s[i] : -Float::INFINITY
	}.max
}
p A.map{|a|
	s = a.sum
	s < 0 ? Max[a,K] : s*(K/a.size) + Max[a,K%a.size]
}.max
