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

Max = lambda{|a,k|
	k = a.size if a.size<k
	next 0 if k <= 0

	l = r = -k
	sl = sr = 0
	ss = [[-Float::INFINITY,0]]
	max = -Float::INFINITY
	while l < a.size-1
		while r < l+k && r < a.size-1
			sr += a[r+=1]
			ss.pop while ! ss.empty? && ss[-1][0] <= sr
			ss << [sr,r]
		end
		xs,xi = ss[0]
		max = xs-sl if max < xs-sl
		sl += a[l+=1]
		ss.shift if ss[0][1] == l
	end

	next max
}

A = P.map{|p|
	a,f = [],lambda{|p|
		a << C[p-1]
		C[p-1] = nil
		next P[p-1]
	}
	q = f[p]
	next unless a[0]
	q = f[q] until q == p
	next a
}.compact

p A.map{|a|
	s = a.sum
	(a.size<K && 0<s) ? s*(K/a.size-1) + Max[a+a,a.size+K%a.size] : Max[a,K]
}.max
