Problem:
Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.

Solution in Rust (1.42.0) (judge verdict: Wrong Answer)

// -*- coding:utf-8-unix -*-

#[macro_use]
extern crate lazy_static;
extern crate num_bigint; // 0.2.2
extern crate num_traits; // 0.2.8
use num_bigint::BigInt;
use num_traits::Pow;

// use proconio::derive_readable;
use proconio::fastout;
use proconio::input;
// use std::convert::TryInto;
use libm::*;
use std::cmp::*;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::io::*;
use std::ops::Range;
use std::str::FromStr;
use superslice::*;

pub fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

//abc175-D
// #[fastout]
fn main() {
    input![n: usize, k: usize, p: [usize; n], c: [i64; n]];
    let p: Vec<_> = p.iter().map(|a| a - 1).collect();

    let mut cycles = Vec::new();
    let mut is_visited = vec![false; n];

    while !is_visited.iter().all(|&a| a) {
        // eprintln!("new cycle before {:?}", cycles);
        let new_cycle = Vec::new();
        cycles.push(new_cycle);

        let (head_idx, _) = is_visited
            .iter()
            .enumerate()
            .find(|(_idx, is_visit)| !*is_visit)
            .unwrap();
        is_visited[head_idx] = true;
        let new_cycle = cycles.last_mut().unwrap();
        new_cycle.push(head_idx);

        let mut current = head_idx;
        loop {
            let next = p[current];
            if next == head_idx {
                break;
            }
            new_cycle.push(next);
            is_visited[next] = true;
            current = next;
        }
    }

    //eprintln!("cycles: {:?}", cycles);

    let mut maxes = Vec::new();
    for cycle in cycles.iter() {
        let can_cycle_num = (k / cycle.len()) as i64;
        let mut remaind = k % cycle.len();
        let cycle_sum: i64 = cycle.iter().map(|x| c[*x]).sum();
        //eprintln!(
        //     "cycle_sum: {:?}, cycle: {:?}, cs: {:?}",
        //     cycle_sum,
        //     cycle,
        //     cycle.iter().map(|x| c[*x]).collect::<Vec<_>>()
        // );

        let mut max_incycle: i64 = 0;
        if cycle_sum > 0 {
            max_incycle += can_cycle_num * cycle_sum;
        }

        let mut max_of_range = -100000000000000;
        if can_cycle_num > 0 && remaind == 0 {
            remaind = cycle.len();
        }

        for s in 0..cycle.len() {
            let mut sum_ranges = vec![0; remaind];
            // let mut sum_range = 0;
            for i in s..(s + remaind) {
                if i - s == 0 {
                    sum_ranges[i - s] = c[cycle[i % cycle.len()]];
                } else {
                    // eprintln!("{},{}", i - s, i % cycle.len());
                    sum_ranges[i - s] = sum_ranges[i - s - 1] + c[cycle[i % cycle.len()]];
                }
            }
            //eprintln!("{}, {}, sum_range: {}", l, s, sum_range);
            max_of_range = max(*sum_ranges.iter().max().unwrap(), max_of_range);
        }

        max_incycle += max_of_range;
        maxes.push(max_incycle);
    }

    //eprintln!("maxes: {:?}", maxes);
    println!("{}", maxes.iter().max().unwrap());
}

fn go(mid: usize, d: usize, use_num: usize, num753_cand: &mut Vec<usize>, n: usize) {}

// use lazy_static::lazy_static;
// use std::sync::Mutex;

// lazy_static! {
//     static ref VALUES: Mutex<Vec<i32>> = Mutex::default();
// }

// let mut values = VALUES.lock().unwrap();
// values.extend_from_slice(&[1, 2, 3, 4]);
// assert_eq!(&*values, &[1, 2, 3, 4]);