N,K = gets.split.map &:to_i
P = gets.split.map{_1.to_i - 1}
C = gets.split.map &:to_i

groups = []
used = []
N.times do |i|
    next if used[i]
    group = []
    j = 0
    until used[i]
        group[j] = i
        used[i] = true
        i = P[i]
        j+=1
    end

    groups << group
end

scores = groups.map do |group|
    total = group.map{C[_1]}.sum * (group.count / K)
    total = [total,0].max

    max = -10**10 
    group.count.times do |i|
        s = 0
        K.times do |offset|
            idx = (i+offset) % group.count
            s += C[group[idx]]
            max = [max,s].max
        end
    end

    total + max
end

p scores.max