console.log((args=>{
  const [[N,K],P,C] = args.trim().split`\n`.map(r=>r.split` `.map(v=>v|0));
  const done = Array(N).fill(false);
  let max = BigInt(Math.max(...C));
  for ( let i = 0; i < N; i++ ) {
    if ( done[i] ) continue;
    let j = i, k = 0, sum = 0;
    const G = [0];
    while ( !done[j] ) {
      done[j] = true;
      G.push(G[k]+C[j]);
      sum += C[j];
      k++;
      j = P[j]-1;
    }
    for ( let i = 1; i <= k; i++ ) G.push(G[k]+G[i]);
    const r = Math.min(K,(sum>0)?K%k:k);
    let cyc = BigInt((sum>0)?sum*Math.floor(K/k):0);
    if ( k===1 && sum>0 && max < cyc) max = cyc;
    else for ( let i = 0; i < k; i++ ) {
      for ( let j = i+1; j <= i+r; j++ ) {
        let s = cyc + BigInt(G[j]-G[i]);
        if ( max < s ) max = s;
      }
    }
  }
  return `${max}`;
})(require('fs').readFileSync('/dev/stdin','utf8')));
