Scanf.scanf "%d %d" (fun n k ->
    let p = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a - 1)) in
    let c = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in

    let par = Array.init n (fun i -> i) in
    
    let rec root x =
        if x = par.(x) then x else
            let r = root par.(x) in
            let () = par.(x) <- r in
            r
    in

    let merge a b =
        if root a <> root b then
            par.(par.(b)) <- par.(a)
    in
    Array.iteri merge p;

    let cluster = Array.init n root in
    let size = Array.make n 0 in
    Array.iter (fun v -> size.(v) <- size.(v) + 1) cluster;

    let sum = Array.make n 0 in

    let calc_loop_score start len =
        let rec loop cur len acc =
            if len = 0 then acc else
                let cur = p.(cur) in
                let acc = acc + c.(cur) in
                loop cur (len - 1) acc
        in
        loop start len 0
    in
    Array.iteri (fun i sz -> if sz > 0 then sum.(i) <- calc_loop_score i sz) size;

    let calc_best start len =
        let rec loop cur len acc mx =
            if len = 0 then mx else
                let cur = p.(cur) in
                let acc = acc + c.(cur) in
                let mx = max mx acc in
                loop cur (len - 1) acc mx
        in
        loop start len 0 (-100000000000000)
    in

    let score = Array.init n (fun i ->
        let cl = cluster.(i) in
        let sz = size.(cl) in
        let kr = k / sz in
        let base = if sum.(cl) > 0 then kr * sum.(cl) else 0 in
        let len = k mod sz in
        let len = if len = 0 then sz else len in
        base + calc_best i len
    ) in
    (*
    Array.iter (Printf.printf "%d ") cluster;
    print_newline ();
    Array.iter (Printf.printf "%d ") size;
    print_newline ();
    Array.iter (Printf.printf "%d ") sum;
    print_newline ();
    Array.iter (Printf.printf "%d ") score;
    print_newline ();
    *)
    Array.fold_left max (-10000000000000) score |> Printf.printf "%d\n"
)