n,k = gets.chomp.split(" ").map(&:to_i)
p = gets.chomp.split(" ").map(&:to_i)
c = gets.chomp.split(" ").map(&:to_i)
ans = -10000000000
visited = Hash.new([-1,0])
1.upto(n) do |i|
  now = i # next = p[now]
  while visited[p[now-1]] == [-1,0]
    visited[p[now-1]] = [0,0]
    now = p[now-1]
  end
  point = 0
  cnt = 0
  arr = []
  while visited[p[now-1]] == [0,0]
    visited[p[now-1]] = [1,0]
    arr << now
    now = p[now-1]
    point += c[p[now-1]-1]
    cnt += 1
  end
  arr.each do |x|
    visited[x] = [cnt,point]
  end
end
puts 0