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.



Sample input:
5 2
2 4 5 1 3
3 4 -10 -8 8


Sample output:
8

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
k_max = 5001
score = [0] * N

for i in range(N):
  exist_i = [(False, -1)] * k_max # (exist, j)
  exist_i[i] = (True, 0)
  score_i = [-10**9-1] * k_max # iからスタートしてK回操作する場合の累積和
  score_i[0] = C[P[i]-1]
  index = P[i]-1
  for j in range(1, K):
    if exist_i[index][0] == True:
      # 既に進んだことがあるマスの場合
      
      # ループ終了インデックスからループ開始インデックスの累積和の差を確認
      loop_score = 0
      if exist_i[index][1] >= 1:
        loop_score = score_i[j-1] - score_i[exist_i[index][1] - 1] # 1ループで増えるスコア
      else:
        loop_score = score_i[j-1]
#      print("i, j, score_i", i, j, score_i)
#      print("i, j, loop_score", i, j, loop_score)
      if loop_score > 0:
        loop_num = j - exist_i[index][1] # ループする要素数
        num = K-j # 残りの操作数
        tmp_score = score_i[j-1] + num // loop_num * loop_score # ループ前までの累積和
#        print("i, j, tmp_score", i, j, tmp_score)
        tmp_array = [0] * (num % loop_num + 1)
        tmp_array[0] = tmp_score
        for l in range(1, num % loop_num + 1):
          tmp_array[l] = tmp_array[l-1] + C[P[index]-1]
          index = P[index]-1
#        print("i, j, tmp_array", i, j, tmp_array)
        score[i] = max(tmp_array)
      else:
#        print("i, j, score_i", i, j, score_i)
        score[i] = max(score_i)
#      print("i, j, score_i", i, j, score_i)
      break
    else:
      if j == K-1:
        score_i[j] = score_i[j-1] + C[P[index]-1]
        score[i] = max(score_i)
#        print("i, j, score_i", i, j, score_i)
        break   
    score_i[j] = score_i[j-1] + C[P[index]-1]
#    print("i, j, score_i", i, j, score_i)
#    print("i, j, score", i, j, score)
    exist_i[index] = (True, j)
    index = P[index]-1
print(max(score))

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/abc175/tasks/abc175_d
# 各ループの1周分の累積和を作ればおけ
# K>ループ長の場合、累積の最後の値が負ならmaxを取ればいいし、正ならば 累積の最後の値*周数をかけてから計算
import sys
sys.setrecursionlimit(1 << 25)
readline = sys.stdin.buffer.readline
read = sys.stdin.readline  # 文字列読み込む時はこっち
ra = range
enu = enumerate


def exit(*argv, **kwarg):
    print(*argv, **kwarg)
    sys.exit()


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def a_int(): return int(readline())


def ints(): return list(map(int, readline().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, readline().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, readline().split())))
    return ret


def read_matrix(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, readline().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter, xor, add
from itertools import product, permutations, combinations, accumulate
from bisect import bisect_left, bisect_right  # , insort_left, insort_right
from functools import reduce
from math import gcd


def lcm(a, b):
    # 最小公倍数
    g = gcd(a, b)
    return a // g * b


N, K = ints()
P = mina(*ints())
C = ints()

scores = [[] for _ in range(N)]  # 各頂点からスタートするscore
for i in range(N):
    # 頂点iからスタートする累積和を作る
    C_i = []
    now = i
    visited = set()
    while P[now] not in visited:
        now = P[now]
        C_i.append(C[now])
        visited.add(now)
    scores[i] = list(accumulate(C_i * 2))


def get_ans(score: list, K: int)->int:
    n = (K - 1) // len(score)  # +n周回ったときにとまる
    pad = score[-1] * (n - 1)
    sco_ = []
    for s in score:
        sco_.append(s + pad)
    pad = score[-1] * (n)
    k = n * len(score)
    for s in score:
        if k == K:
            break
        sco_.append(s + pad)
        k += 1
    # print(sco_)
    return max(sco_)


# print(scores)
ans = -10**10 - 114514
for i in range(N):
    score = scores[i]
    if len(score) > K or score[-1] <= 0:
        # if len(score) > + K:
        ans = max(ans, max(score))
    else:  # 何周もしたほうが良い
        # print(i)
        ans = max(ans, get_ans(score, K))


print(ans)

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/abc175/tasks/abc175_d
# 各ループの1周分の累積和を作ればおけ
# K>ループ長の場合、累積の最後の値が負ならmaxを取ればいいし、正ならば 累積の最後の値*周数をかけてから計算
import sys
sys.setrecursionlimit(1 << 25)
readline = sys.stdin.buffer.readline
read = sys.stdin.readline  # 文字列読み込む時はこっち
ra = range
enu = enumerate


def exit(*argv, **kwarg):
    print(*argv, **kwarg)
    sys.exit()


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def a_int(): return int(readline())


def ints(): return list(map(int, readline().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, readline().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, readline().split())))
    return ret


def read_matrix(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, readline().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter, xor, add
from itertools import product, permutations, combinations, accumulate
from bisect import bisect_left, bisect_right  # , insort_left, insort_right
from functools import reduce
from math import gcd


def lcm(a, b):
    # 最小公倍数
    g = gcd(a, b)
    return a // g * b


N, K = ints()
P = mina(*ints())
C = ints()

scores = [[] for _ in range(N)]  # 各頂点からスタートするscore
for i in range(N):
    # 頂点iからスタートする累積和を作る
    C_i = []
    now = i
    visited = set()
    while P[now] not in visited:
        now = P[now]
        C_i.append(C[now])
        visited.add(now)
    scores[i] = list(accumulate(C_i))


def get_ans(score: list, K: int)->int:
    n = (K - 1) // len(score)  # +n周回ったときにとまる
    pad = score[-1] * (n - 1)
    sco_ = []
    for s in score:
        sco_.append(s + pad)
    pad = score[-1] * (n)
    k = n * len(score)
    for s in score:
        if k == K:
            break
        sco_.append(s + pad)
        k += 1
    # print(sco_)
    return max(sco_)


# print(scores)
ans = -10**10 - 114514
for i in range(N):
    score = scores[i]
    if len(score) >= K or score[-1] <= 0:
        # if len(score) > + K:
        ans = max(ans, max(score))
    else:  # 何周もしたほうが良い
        # print(i)
        ans = max(ans, get_ans(score, K))


print(ans)

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/abc175/tasks/abc175_d
# 各ループの1周分の累積和を作ればおけ
# K>ループ長の場合、累積の最後の値が負ならmaxを取ればいいし、正ならば 累積の最後の値*周数をかけてから計算
import sys
sys.setrecursionlimit(1 << 25)
readline = sys.stdin.buffer.readline
read = sys.stdin.readline  # 文字列読み込む時はこっち
ra = range
enu = enumerate


def exit(*argv, **kwarg):
    print(*argv, **kwarg)
    sys.exit()


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def a_int(): return int(readline())


def ints(): return list(map(int, readline().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, readline().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, readline().split())))
    return ret


def read_matrix(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, readline().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter, xor, add
from itertools import product, permutations, combinations, accumulate
from bisect import bisect_left, bisect_right  # , insort_left, insort_right
from functools import reduce
from math import gcd


def lcm(a, b):
    # 最小公倍数
    g = gcd(a, b)
    return a // g * b


N, K = ints()
P = mina(*ints())
C = ints()

scores = [[] for _ in range(N)]  # 各頂点からスタートするscore
for i in range(N):
    # 頂点iからスタートする累積和を作る
    C_i = []
    now = i
    visited = set()
    while P[now] not in visited:
        now = P[now]
        C_i.append(C[now])
        visited.add(now)
    scores[i] = list(accumulate(C_i))


def get_ans(score: list, K: int)->int:
    n = (K - 1) // len(score)  # +n周回ったときにとまる
    pad = score[-1] * (n - 1)
    sco_ = []
    for s in score:
        sco_.append(s + pad)
    pad = score[-1] * (n)
    k = n * len(score)
    for s in score:
        if k == K:
            break
        sco_.append(s + pad)
        k += 1
    # print(sco_)
    return max(sco_)


# print(scores)
ans = -10**10 - 114514
for i in range(N):
    score = scores[i]
    if len(score) > K or score[-1] <= 0:
        ans = max(ans, max(score))
    else:  # 何周もしたほうが良い
        # print(i)
        ans = max(ans, get_ans(score, K))


print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    n,k = map(int,input().split())
    p = list(map(int,input().split()))
    c = list(map(int,input().split()))
    G = [0] * n
    g = 1
    for i in range(n):
        if G[i] == 0:
            G[i] = g
            nxt = p[i] - 1
            while True:
                if G[nxt] == 0:
                    G[nxt] = g
                    nxt = p[nxt] -1
                else:
                    break
            g += 1
    G_sum = [0] * max(G)
    G_len = [0] * max(G)
    for i, g in enumerate(G):
        G_sum[g-1] += c[i]
        G_len[g-1] += 1
    ans = -1 * float('inf')
    for i in range(n):
        s = 0
        loop = k//G_len[G[i]-1]
        amari = k - loop * G_len[G[i]-1]
        if amari == 0:
            amari = G_len[G[i]-1]
            loop -= 1
        nxt = p[i] - 1
        for _ in range(amari):
            s += c[nxt]
            nxt = p[nxt] - 1
            if s>ans:
                ans = s
        s += loop * G_sum[G[i]-1]
        if s>ans:
            ans = s
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def main():
    n,k = map(int,input().split())
    p = list(map(int,input().split()))
    c = list(map(int,input().split()))
    loop = [0 for i in range(n)]
    g = 1
    for i in range(n):
        if loop[i] != 0:
            continue
        loop[i] = g
        nxt = i
        while True:
            if loop[p[nxt]-1] == 0:
                loop[p[nxt]-1] = g
                nxt = p[nxt]-1
            else:
                break
        g += 1
    G,loop_sum = {},{}
    for key in range(max(loop)):
        G[key+1] = []
    for i, l in enumerate(loop):
        G[l].append(i)
    for key in G.keys():
        s = 0
        for i in G[key]:
            s += c[i]
        loop_sum[key] = s
    ans = -1 * float('inf')
    for i in range(n):
        g = loop[i]
        l_s = loop_sum[g]
        l = len(G[g])
        S = -1 * float('inf')
        s = 0
        nxt = i
        if l>=k:
            for _ in range(k):
                s += c[p[nxt]-1]
                nxt = p[nxt]-1
                if s>S:
                    S = s
            if S>ans:
                ans = S
        else:
            l_cnt = k//l
            rest = k - l_cnt * l
            if rest == 0:
                rest = l
                l_cnt -= 1
            for _ in range(rest):
                s += c[p[nxt]-1]
                nxt = p[nxt] - 1
                if s>S:
                    S = s
            if s + l_s * l_cnt > S:
                S = s + l_s * l_cnt
            if S > ans:
                ans = S
            
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18+7
R = 10**9 + 7
#R = 998244353

def ddprint(x):
  if DBG:
    print(x)

n,k = inm()
p = inl()
c = inl()
p = [x-1 for x in p]
used = [False]*n
mx = -BIG
for i in range(n):
    if used[i]:
        continue
    j = p[i]
    used[i] = used[j] = True
    pt = c[j]
    ids = [i,j]
    acc = [0,pt]
    while j!=i:
        j = p[j]
        used[j] = True
        pt += c[j]
        ids.append(j)
        acc.append(pt)
    ids.pop()
    cycsum = acc[-1]
    t = len(ids)
    mx = max(mx, cycsum*(k//t))
    if cycsum<0 and k>=t:
        mx = max(mx, cycsum)
    for j in range(1,t):
        acc.append(acc[j]+cycsum)
    #ddprint(f"{ids=} {acc=} {cycsum=} {t=}")
    for j in range(t):
        for m in range(1,min(k+1,t)):
            mx = max(mx, acc[j+m]-acc[j]+max(0,cycsum*((k-m)//t)))
print(mx)

Submission status: Wrong Answer

Solution code:
#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7
#R = 998244353

def ddprint(x):
  if DBG:
    print(x)

n,k = inm()
p = inl()
c = inl()
p = [x-1 for x in p]
used = [False]*n
mx = -BIG
for i in range(n):
    if used[i]:
        continue
    j = p[i]
    used[i] = used[j] = True
    pt = c[j]
    ids = [i,j]
    acc = [0,pt]
    while j!=i:
        j = p[j]
        used[j] = True
        pt += c[j]
        ids.append(j)
        acc.append(pt)
    ids.pop()
    cycsum = acc[-1]
    t = len(ids)
    mx = max(mx, cycsum*(k//t))
    if cycsum<0 and k>=t:
        mx = max(mx, cycsum)
    for j in range(1,t):
        acc.append(acc[j]+cycsum)
    #ddprint(f"{ids=} {acc=} {cycsum=} {t=}")
    for j in range(t):
        for m in range(1,min(k+1,t)):
            mx = max(mx, acc[j+m]-acc[j]+max(0,cycsum*((k-m)//t)))
print(mx)

Submission status: Wrong Answer

Solution code:
#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7
#R = 998244353

def ddprint(x):
  if DBG:
    print(x)

n,k = inm()
p = inl()
c = inl()
p = [x-1 for x in p]
used = [False]*n
mx = -BIG
for i in range(n):
    if used[i]:
        continue
    j = p[i]
    used[i] = used[j] = True
    pt = c[j]
    ids = [i,j]
    acc = [0,pt]
    while j!=i:
        j = p[j]
        used[j] = True
        pt += c[j]
        ids.append(j)
        acc.append(pt)
    ids.pop()
    cycsum = acc[-1]
    t = len(ids)
    mx = max(mx, cycsum*(k//t))
    if cycsum<0 and k>=t:
        mx = max(mx, cycsum)
    for j in range(1,t):
        acc.append(acc[j]+cycsum)
    #ddprint(f"{ids=} {acc=} {cycsum=} {t=}")
    for j in range(t):
        for m in range(1,min(k+1,t+1)):
            mx = max(mx, acc[j+m]-acc[j]+max(0,cycsum*((k-m)//t)))
print(mx)

Submission status: Wrong Answer

Solution code:
#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7
#R = 998244353

def ddprint(x):
  if DBG:
    print(x)

n,k = inm()
p = inl()
c = inl()
p = [x-1 for x in p]
used = [False]*n
mx = -BIG
for i in range(n):
    if used[i]:
        continue
    j = p[i]
    used[i] = used[j] = True
    pt = c[j]
    ids = [i,j]
    acc = [0,pt]
    while j!=i:
        j = p[j]
        used[j] = True
        pt += c[j]
        ids.append(j)
        acc.append(pt)
    ids.pop()
    cycsum = acc[-1]
    t = len(ids)
    mx = max(mx, cycsum*(k//t))
    if cycsum<0:
        mx = max(mx, cycsum)
    for j in range(1,t):
        acc.append(acc[j]+cycsum)
    for j in range(t):
        for m in range(1,min(k+1,t+1)):
            mx = max(mx, acc[j+m]-acc[j]+max(0,cycsum*((k-m)//t)))
print(mx)

Submission status: Wrong Answer

Solution code:
#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7
#R = 998244353

def ddprint(x):
  if DBG:
    print(x)

n,k = inm()
p = inl()
c = inl()
p = [x-1 for x in p]
used = [False]*n
mx = -BIG
for i in range(n):
    if used[i]:
        continue
    j = p[i]
    used[i] = used[j] = True
    pt = c[j]
    ids = [i,j]
    acc = [0,pt]
    while j!=i:
        j = p[j]
        used[j] = True
        pt += c[j]
        ids.append(j)
        acc.append(pt)
    ids.pop()
    cycsum = acc[-1]
    t = len(ids)
    mx = max(mx, cycsum*(k//t))
    if cycsum<0:
        mx = max(mx, cycsum)
    for j in range(1,t):
        acc.append(acc[j]+cycsum)
    for j in range(t):
        for m in range(1,min(k+1,t)):
            mx = max(mx, acc[j+m]-acc[j]+max(0,cycsum*((k-m)//t)))
print(mx)

Submission status: Wrong Answer

Solution code:
#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7
#R = 998244353

def ddprint(x):
  if DBG:
    print(x)

n,k = inm()
p = inl()
c = inl()
p = [x-1 for x in p]
used = [False]*n
mx = -BIG
for i in range(n):
    if used[i]:
        continue
    j = p[i]
    used[i] = used[j] = True
    pt = c[j]
    ids = [i,j]
    acc = [0,pt]
    while j!=i:
        j = p[j]
        used[j] = True
        pt += c[j]
        ids.append(j)
        acc.append(pt)
    ids.pop()
    cycsum = acc[-1]
    t = len(ids)
    mx = max(mx, max(0,cycsum*(k//t)))
    for j in range(1,t):
        acc.append(acc[j]+cycsum)
    for j in range(t):
        for m in range(1,min(k+1,t)):
            mx = max(mx, acc[j+m]-acc[j]+max(0,cycsum*((k-m)//t)))
print(mx)

Submission status: Wrong Answer

Solution code:
#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7
#R = 998244353

def ddprint(x):
  if DBG:
    print(x)

n,k = inm()
p = inl()
c = inl()
p = [x-1 for x in p]
used = [False]*n
mx = -BIG
for i in range(n):
    if used[i]:
        continue
    j = p[i]
    used[i] = used[j] = True
    pt = c[j]
    ids = [i,j]
    acc = [0,pt]
    while j!=i:
        j = p[j]
        used[j] = True
        pt += c[j]
        ids.append(j)
        acc.append(pt)
    ids.pop()
    cycsum = acc[-1]
    t = len(ids)
    mx = max(mx, cycsum*(k//t))
    for j in range(1,t):
        acc.append(acc[j]+cycsum)
    for j in range(t):
        for m in range(1,min(k+1,t)):
            mx = max(mx, acc[j+m]-acc[j]+max(0,cycsum*((k-m)//t)))
print(mx)

Submission status: Wrong Answer

Solution code:
#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7
#R = 998244353

def ddprint(x):
  if DBG:
    print(x)

n,k = inm()
p = inl()
c = inl()
p = [x-1 for x in p]
used = [False]*n
mx = -BIG
for i in range(n):
    if used[i]:
        continue
    j = p[i]
    used[i] = used[j] = True
    pt = c[j]
    ids = [i,j]
    acc = [0,pt]
    while j!=i:
        j = p[j]
        used[j] = True
        pt += c[j]
        ids.append(j)
        acc.append(pt)
    ids.pop()
    cycsum = acc[-1]
    t = len(ids)
    for j in range(1,t):
        acc.append(acc[j]+cycsum)
    for j in range(t):
        for m in range(1,min(k+1,t)):
            mx = max(mx, acc[j+m]-acc[j]+max(0,cycsum*((k-m)//t)))
print(mx)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
Pn=list(map(int,input().split()))
Cn=list(map(int,input().split()))
Score=0
m=min(Cn)
ScoreList=m
ScoreMAX=m
if max(Cn)<0:
    print(max(Cn))
else:
    for i in range(N):
        Score=0
        ScoreList=m
        t=i
        j=0
        while j <=K-1:
            Score=Score+Cn[t]
            ScoreList=max(ScoreList,Score)
            t=Pn[t]-1
            j=j+1
    ScoreMAX=max(ScoreMAX,ScoreList)
    print(ScoreMAX)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
Pn=list(map(int,input().split()))
Cn=list(map(int,input().split()))
Score=0
m=min(Cn)
ScoreList=m
ScoreMAX=m
for i in range(N):
    Score=0
    ScoreList=m
    t=i
    j=0
    while j <=K:
        Score=Score+Cn[t]
        ScoreList=max(ScoreList,Score)
        t=Pn[t]-1
        j=j+1
    ScoreMAX=max(ScoreMAX,ScoreList)
print(ScoreMAX)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
Pn=list(map(int,input().split()))
Cn=list(map(int,input().split()))
Score=0
ScoreList=[]
ScoreMAX=-10000
for i in range(N):
    Score=0
    ScoreList=[]
    t=i
    j=0
    while j <=K:
        Score=Score+Cn[t]
        ScoreList.append(Score)
        t=Pn[t]-1
        j=j+1
    ScoreMAX=max(ScoreMAX,max(ScoreList))
print(ScoreMAX)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
pp = list(map(int, input().split()))
p = [pp[i]-1 for i in range(n)]
c = list(map(int, input().split()))

ans = -(10**9+1)
for i in range(n):
  s = 0
  x = i
  for j in range(k):
    x = p[x]
    s += c[x]
    ans = max(ans,s)
    if i == x:
      break
  a = int(k/(j+1))
  m = k%(j+1)
  if m == 0 and a > 1:
    m = k+1
    a -= 1
  s *= a
  ans = max(ans,s)
  for l in range(m):
    x = p[x]
    s += c[x]
    ans = max(ans, s)
print (ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Ps = [i - 1 for i in Ps]
Cs = list(map(int, input().split()))
max_score = -float("inf")


for i in range(N):
  scores = []
  idx = i  # starting index
  while True:
    idx = Ps[idx]  # point to the next index
    scores.append(Cs[idx])  # fetch a score to add
    if idx == i:  # when the cycle is closed
      break
  len_cycle = len(scores)
  sum_cycle = sum(scores)
  
  if sum_cycle <= 0:  # when each cycle reduces the total score
    score = 0
    for j in range(min(K, len_cycle)):
      score += scores[j]
      max_score = max(max_score, score)
  else:
    score = sum_cycle * (K // len_cycle)
    max_score = max(max_score, score)
    for j in range(K % len_cycle):
      score += scores[j]
      max_score = max(max_score, score)
    
print(max_score)

Submission status: Wrong Answer

Solution code:

N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Ps = [i - 1 for i in Ps]
Cs = list(map(int, input().split()))
max_score = -float("inf")


for i in range(N):
    scores = []
    idx = i  # starting index
    while True:
        idx = Ps[idx]  # point to the next index
        scores.append(Cs[idx])  # fetch a score to add
        if idx == i:  # when the cycle is closed
            break
    len_cycle = len(scores)
    sum_cycle = sum(scores)

    if sum_cycle <= 0:  # when each cycle reduces the total score
        score = 0
        for j in range(min(K, len_cycle)):
            score += scores[j]
            max_score = max(max_score, score)
    else:
        score = sum_cycle * (K // len_cycle)
        if K % len_cycle == 0:
            max_score = max(max_score, score)
        for j in range(K % len_cycle):
            score += scores[j]
            max_score = max(max_score, score)

print(max_score)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Ps = [i - 1 for i in Ps]
Cs = list(map(int, input().split()))
max_score = -float("inf")


for i in range(N):
  scores = []
  idx = i  # starting index
  while True:
    idx = Ps[idx]  # point to the next index
    scores.append(Cs[idx])  # fetch a score to add
    if idx == i:  # when the cycle is closed
      break
  len_cycle = len(scores)
  sum_cycle = sum(scores)
  
  if sum_cycle <= 0:  # when each cycle reduces the total score
    score = 0
    for j in range(min(K, len_cycle)):
      score += scores[j]
      max_score = max(max_score, score)
  else:
    score = sum_cycle * (K // len_cycle)
    for j in range(K % len_cycle):
      score += scores[j]
      max_score = max(max_score, score)
    
print(max_score)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Cs = list(map(int, input().split()))

def calcScore(C_list, P_list, idx, num_operation):
  score = 0
  for i in range(num_operation):
    score += C_list[P_list[idx] - 1]
    if i == 0:
      max_score = score
    else:
      max_score = max(max_score, score)
  return max_score

max_scores = [calcScore(Cs, Ps, i, K) for i in range(N)]

print(max(max_scores))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = [0] + list(map(int, input().split()))
c = [0] + list(map(int, input().split()))

freq = [0] * (n+1)
x = [0] * (n+1)
score = [[0] for _ in range(n+1)]
for i in range(1, n+1):
    check = [False] * (n+1)
    check[i] = True
    now = i
    cnt = 0
    while True:
        if check[p[now]]:
            x[i] = score[i][-1] + c[p[now]]
            score[i].append(c[p[now]] + score[i][-1])
            freq[i] = cnt + 1
            break

        now = p[now]
        check[now] = True
        score[i].append(c[now] + score[i][-1])
        cnt += 1

ans = min(c)
for i in range(1, n+1):
    if freq[i] <= k:
        if x[i] > 0:
            tmp = k % freq[i]
            ans = max(
                ans, max(score[i][:tmp + 1]) + (k//freq[i]) * x[i]
            )
        else:
            tmp = freq[i]
            ans = max(
                ans, max(score[i][1:tmp + 1])
            )
    else:
        tmp = k
        ans = max(
            ans, max(score[i][1:tmp + 1])
        )

print(ans)
#print(*x)
#print(*freq)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = [0] + list(map(int, input().split()))
c = [0] + list(map(int, input().split()))

freq = [0] * (n+1)
x = [0] * (n+1)
score = [[0] for _ in range(n+1)]
for i in range(1, n+1):
    check = [False] * (n+1)
    check[i] = True
    now = i
    cnt = 0
    while True:
        if check[p[now]]:
            x[i] = score[i][-1] + c[p[now]]
            score[i].append(c[p[now]] + score[i][-1])
            freq[i] = cnt + 1
            break

        now = p[now]
        check[now] = True
        score[i].append(c[now] + score[i][-1])
        cnt += 1

ans = min(c)
for i in range(1, n+1):
    if freq[i] <= k:
        if x[i] >= 0:
            tmp = k % freq[i]
            ans = max(
                ans, max(score[i][:tmp + 1]) + (k//freq[i]) * x[i]
            )
        else:
            tmp = freq[i]
            ans = max(
                ans, max(score[i][1:tmp + 1])
            )
    else:
        tmp = k
        ans = max(
            ans, max(score[i][1:tmp + 1])
        )

print(ans)
#print(*x)
#print(*freq)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = [0] + list(map(int, input().split()))
c = [0] + list(map(int, input().split()))

freq = [0] * (n+1)
x = [0] * (n+1)
score = [[0] for _ in range(n+1)]
for i in range(1, n+1):
    check = [False] * (n+1)
    check[i] = True
    now = i
    cnt = 0
    while True:
        if check[p[now]]:
            x[i] = score[i][-1] + c[p[now]]
            score[i].append(c[p[now]] + score[i][-1])
            freq[i] = cnt + 1
            break

        now = p[now]
        check[now] = True
        score[i].append(c[now] + score[i][-1])
        cnt += 1

ans = -10**10
for i in range(1, n+1):
    if freq[i] <= k:
        if x[i] > 0:
            tmp = k % freq[i]
            ans = max(
                ans, max(score[i][:tmp + 1]) + (k//freq[i]) * x[i]
            )
        else:
            tmp = freq[i]
            ans = max(
                ans, max(score[i][1:tmp + 1])
            )
    else:
        tmp = k
        ans = max(
            ans, max(score[i][1:tmp + 1])
        )

print(ans)
print(*x)
print(*freq)