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 C# (Mono-mcs 6.8.0.105) (judge verdict: Wrong Answer)

using System;
using System.Collections.Generic;
using System.Windows;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Atcoder
{
    public class Program
    {
        private static long mod = 1000000007;
        private static long max = 999999999999;

        static void Main(string[] args)
        {
            var r = ReadSplit();
            var n = r[0].Int();
            var k = r[1].Long();
            var pl = new long[n + 1];
            var cl = new long[n + 1];
            var rp = ReadSplit();
            var rc = ReadSplit();
            for (int i = 0; i < n; i++)
            {
                pl[i] = rp[i].Long();
                cl[i] = rc[i].Long();
            }

            //var roop = k / 5000;
            //var sub = k % 5000;
            //if (k >= 5000)
            //{
            //    k = 5000;
            //}

            long ans = -1 * max;
            for (int i = 0; i < n; i++)
            {
                var dic = new long[n + 10];
                long tmp = 0;
                var now = pl[i];
                long roopTmp = 0;
                long breakCount = 0;
                long roopStart = -1;
                for (int j = 0; j < k; j++)
                {
                    tmp += cl[now - 1];
                    
                    if(dic[now] == 1)
                    {
                        roopTmp += cl[now - 1];
                        if (roopStart == -1)
                        {
                            roopStart = now;
                        }
                    }
                    if (dic[now] == 2)
                    {
                        breakCount = j;
                        break;
                    }
                    dic[now]++;
                    
                    now = pl[now - 1];
                    ans = Math.Max(tmp, ans);
                }
                long rCount = dic.Count(x => x == 2);
                if (k > breakCount && roopTmp > 0)
                {
                    var mul = (k - breakCount) / rCount;
                    var zan = (k - breakCount) % rCount;
                    tmp += mul * roopTmp;
                    tmp -= cl[now - 1];
                    ans = Math.Max(tmp, ans);
                    now = roopStart;
                    for (int m = 0; m < zan; m++)
                    {
                        tmp += cl[now - 1];
                        now = pl[now - 1];
                        ans = Math.Max(tmp, ans);
                    }
                }

            }

            WriteRead(ans);
        }

        private static void Dfs(int key, int par, int[] ans, Dictionary<int, List<int>> dic)
        {
            var color = 1;
            if (!dic.ContainsKey(key))
            {
                return;
            }
            foreach (var item in dic[key])
            {
                if (color == par)
                {
                    color++;
                }
                ans[item] = color;
                Dfs(item, color, ans, dic);
                color++;
            }
        }

        public static List<long> GetCalcDivisor(long n)
        {
            var res = new List<long>();
            for (long i = 1L; i * i <= n; ++i)
            {
                if (n % i == 0)
                {
                    res.Add(i);
                    long j = n / i;
                    if (j != i) res.Add(j);
                }
            }
            res.Sort();
            return res;
        }

        class ModCombination
        {
            public long _mod = 1000000007;
            public int _max = 1000000;

            long[] fac;
            long[] finv;
            long[] inv;

            public ModCombination() : this(1000000007, 1000000)
            {
            }

            public ModCombination(long mod, int max)
            {
                _mod = mod;
                _max = max;
                fac = new long[max];
                finv = new long[max];
                inv = new long[max];
                fac[0] = fac[1] = 1;
                finv[0] = finv[1] = 1;
                inv[1] = 1;
                for (int i = 2; i < max; i++)
                {
                    fac[i] = fac[i - 1] * i % mod;
                    inv[i] = mod - inv[mod % i] * (mod / i) % mod;
                    finv[i] = finv[i - 1] * inv[i] % mod;
                }
            }

            public long Combination(int n, int m)
            {
                if (n < m) return 0;
                if (n < 0 || m < 0) return 0;
                return fac[n] * (finv[m] * finv[n - m] % _mod) % _mod;
            }
        }

        public static string Read()
        {
            return Console.ReadLine();
        }

        public static string[] ReadSplit()
        {
            return Console.ReadLine().Split(' ');
        }

        public static void WriteRead(object str)
        {
            Console.WriteLine(str);
            Read();
        }

        public static void Write(object str)
        {
            Console.WriteLine(str);
        }

        private static bool ChangeMin<T>(ref T a, T b) where T : IComparable
        {
            if (a.CompareTo(b) > 0)
            {
                a = b;
                return true;
            }
            return false;
        }

        private static bool ChangekMax<T>(ref T a, T b) where T : IComparable
        {
            if (b.CompareTo(a) > 0)
            {
                a = b;
                return true;
            }
            return false;
        }

        /*優先度付きキュー*/
        class PriorityQueue<T> where T : IComparable<T>
        {
            public readonly T[] Array;
            public readonly bool Greater;
            public int Count { get; private set; } = 0;

            public PriorityQueue(int capacity, bool greater = true)
            {
                this.Array = new T[capacity];
                this.Greater = greater;
            }

            public void Enqueue(T item)
            {
                this.Array[this.Count] = item;
                this.Count += 1;
                this.UpHeap();
            }

            public T Dequeue()
            {
                // 先頭要素を末尾にして再構成
                this.Swap(0, this.Count - 1);
                this.Count -= 1;
                this.DownHeap();

                return this.Array[this.Count];
            }


            private void UpHeap()
            {
                var n = this.Count - 1;
                while (n != 0)
                {
                    // 親要素の座標
                    var parent = (n - 1) / 2;

                    if (this.Compare(this.Array[n], this.Array[parent]) > 0)
                    {
                        this.Swap(n, parent);
                        n = parent;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            private void DownHeap()
            {
                var parent = 0;
                while (true)
                {
                    var child = 2 * parent + 1;
                    if (child > this.Count - 1) break;

                    if (child < this.Count - 1 && this.Compare(this.Array[child], this.Array[child + 1]) < 0)
                    {
                        // 左より右の子のほうが大きい値の場合、右を入れ替え対象にする
                        child += 1;
                    }

                    if (this.Compare(this.Array[parent], this.Array[child]) < 0)
                    {
                        this.Swap(parent, child);
                        parent = child;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            //aとbを比較する
            private int Compare(T a, T b)
            {
                var c = a.CompareTo(b);
                if (!this.Greater)
                {
                    c = -c;
                }
                return c;
            }

            //aとbを入れ替える
            private void Swap(int a, int b)
            {
                var tmp = this.Array[a];
                this.Array[a] = this.Array[b];
                this.Array[b] = tmp;
            }
        }

        private static bool NextPermutation(int[] array)
        {
            var size = array.Length;
            var ok = false;

            //array[i]<array[i+1]を満たす最大のiを求める
            int i = size - 2;
            for (; 0 <= i; i--)
            {
                if (array[i] < array[i + 1])
                {
                    ok = true;
                    break;
                }
            }

            //全ての要素が降順の場合、NextPermutationは存在しない
            if (ok == false) return false;

            //array[i]<array[j]を満たす最大のjを求める
            int j = size - 1;
            for (; ; j--)
            {
                if (array[i] < array[j]) break;
            }

            //iとjの要素をswapする
            var tmp = array[i];
            array[i] = array[j];
            array[j] = tmp;

            //i以降の要素を反転させる
            Array.Reverse(array, i + 1, size - (i + 1));

            return true;
        }

        //要素数Nを引数として渡し、0～N-1でできた順列をすべて返す
        static List<int[]> GetAllPermutation(int N)
        {
            var res = new List<int[]>();
            var array = Enumerable.Range(0, N).ToArray();
            do
            {
                var copy = new int[N];
                array.CopyTo(copy, 0);
                res.Add(copy);
            } while (NextPermutation(array));

            return res;
        }

        //配列arrayを引数として渡し,辞書順がarray以上の順列をすべて返す
        static List<int[]> GetAllPermutation(int[] array)
        {
            var size = array.Length;
            var res = new List<int[]>();
            do
            {
                var copy = new int[size];
                array.CopyTo(copy, 0);
                res.Add(copy);
            } while (NextPermutation(array));

            return res;
        }

        public static long ModPow(long x, long n)
        {
            x = x % mod;
            if (n == 0)
            {
                return 1;
            }
            else if (n % 2 == 1)
            {
                return (x * ModPow(x, n - 1)) % mod;
            }
            else
            {
                return ModPow((x * x) % mod, n / 2) % mod;
            }
        }

        /// <summary>
        /// 最小公倍数
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static long Lcm(long a, long b)
        {
            return a / Gcd(a, b) * b;
        }
        /// <summary>
        /// 最大公約数
        /// </summary>
        /// <param name="m"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static long Gcd(long m, long n)
        {
            if (n == 0) return m;
            return Gcd(n, m % n);
        }
    }
}


public static class Extentions
{
    public static int Int(this object obj)
    {
        return int.Parse(obj.ToString());
    }

    public static long Long(this object obj)
    {
        return long.Parse(obj.ToString());
    }

    public static decimal Decimal(this object obj)
    {
        return decimal.Parse(obj.ToString());
    }

    public static double Double(this object obj)
    {
        return double.Parse(obj.ToString());
    }

    public static T2 GetValueZero<T1, T2>(this Dictionary<T1, T2> d, T1 key) where T2 : struct
    {
        T2 value;
        if (d.TryGetValue(key, out value))
        {
            return value;
        }
        return new T2();
    }
}