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(-2e18);
  for ( let i = 0; i < N; i++ ) {
    if ( done[i] ) continue;
    done[i] = true;
    let j = P[i]-1, k = 1, sum = C[i];
    const G = [C[i]];
    while ( j !== i ) {
      done[j] = true;
      G.push(G[k-1]+C[j]);
      sum += C[j];
      k++;
      j = P[j]-1;
    }
    for ( let i = 0; i < k; i++ ) G.push(G[k-1]+G[i]);
    const r = Math.min(K,(sum>0)?K%k:k);
    let cyc = BigInt((sum>0)?sum*Math.floor(K/k):0);
    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')));
