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:
N,K=list(map(int,input().split()))
P=list(map(int,input().split()))
C=list(map(int,input().split()))
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

Q=[]
uf=UnionFind(N)
for i in range(N):
    uf.union(i,P[i]-1)
D1=list(uf.all_group_members().values())
D2=[]
for i in D1:
    ans=0
    for j in i:
        ans+=C[j]
    D2.append(ans)
L=[len(i) for i in D1]
S=min(2*max(L),K)

for i in range(N):
    ans=-float('inf')
    ans1=0
    now=P[i]-1
    for j in range(S):
        ans1+=C[now]
        now=P[now]-1
        ans=max(ans1,ans)
    Q.append(ans)
    
if K>min(L):
    for i,value in enumerate(D2):
        if value>0:
            ans3=value*(K//L[i])
            for j in D1[i]:
                ans=-float('inf')
                ans1=0
                now=P[j]-1
                for k in range(K%L[i]):
                    ans1+=C[now]
                    now=P[now]-1
                    ans=max(ans1,ans)
                Q.append(ans3+ans)
print(max(Q))

Submission status: Wrong Answer

Solution code:
N,K=map(int, input().split())
P=list(map(int, input().split()))
C=list(map(int, input().split()))

F=[0]*N
I=[0]*N
CN=[0]*N

for i in range(N):
  around=0
  cnt=0
  A=[]
  if F[i]==0:
    F[i]=1
    around+=1
    cnt+=C[i]
    nex=P[i]-1
    A.append(i)
    while F[nex]==0:
      A.append(nex)
      F[nex]=1
      around+=1
      cnt+=C[nex]
      nex=P[nex]-1
    for j in A:
      I[j]=around
      CN[j]=cnt
#print(F)
#print(I)
#print(CN)
ans=-(10**9)*2
for i in range(N):
  cnt=C[i]
  #動かす回数が一周に満たない時
  if (K+1)<=I[i]:
    d=0
    nex=i
    for j in range(K+1):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
  #動かす回数が一周を超えるとき
  elif CN[i]<=0:
    d=0
    nex=i
    for j in range(I[i]):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
  else:
    d=0
    nex=i
    for j in range(I[i]):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
    acnt=cnt
    bcnt=C[i]
    syuukai=(K+1)//I[i]
    nokori=(K+1)%I[i]
    syuukai-=1
    nokori+=I[i]
    d=0
    nex=i
    for j in range(nokori-1):
      d+=C[nex]
      nex=P[nex]-1
      bcnt=max(d,bcnt)
    bcnt+=syuukai*CN[i]
    cnt=max(acnt,bcnt)
  ans=max(ans,cnt)
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1  # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7


def debug(*x):
    print(*x, file=sys.stderr)


def solve0(N, K, PS, CS):
    PS = [x - 1 for x in PS]
    CS = [CS[PS[i]] for i in range(N)]
    PSS = [PS]
    CSS = [CS]
    prevPS = PS
    prevCS = CS
    for i in range(30):
        PS2 = [prevPS[prevPS[i]] for i in range(N)]
        CS2 = [prevCS[i] + prevCS[prevPS[i]] for i in range(N)]
        PSS.append(PS2)
        CSS.append(CS2)
        prevPS = PS2
        prevCS = CS2

    score = [0] * N
    pos = list(range(N))
    length = [0] * N
    maxbit = K.bit_length() - 1
    for i in range(maxbit, -1, -1):
        # debug(": i", i)
        # debug(": 2**i", 2**i)
        # debug(": CSS[i]", CSS[i])
        # debug(": PSS[i]", PSS[i])
        # debug(": score", score)
        # debug(": length", length)
        for j in range(N):
            # debug(": length[j] + 2 ** i <= K", length[j] + 2 ** i <= K)
            # debug(": CSS[i][pos[j]]", CSS[i][pos[j]])
            if length[j] + 2 ** i <= K and CSS[i][pos[j]] > 0:
                # debug("add: j", j)
                score[j] += CSS[i][pos[j]]
                pos[j] = PSS[i][pos[j]]
                length[j] += 2 ** i
            # if CSS[i][j] > score[j]:
            #     # debug("reset: j", j)
            #     # debug(": CSS[i][i], score[j]", CSS[i][i], score[j])
            #     pos[j] = PSS[i][j]
            #     score[j] = CSS[i][j]
            #     length[j] = 2 ** i

    # debug("finish: score", score)
    ret = max(score)
    if ret == 0:
        ret = max(CS)
    return ret


def solve(N, K, PS, CS):
    ret = solve0(N, K, PS, CS)
    PS = [x - 1 for x in PS]
    CS = [CS[PS[i]] for i in range(N)]
    visited = {}
    loops = []
    loopScore = []
    for i in range(N):
        loop = []
        c = 0
        while i not in visited:
            visited[i] = True
            c += CS[i]
            i = PS[i]
            loop.append(i)
        if loop:
            loops.append(loop)
            loopScore.append(c)
    # debug(": loops", loops)
    # debug(": loopScore", loopScore)

    return ret


def main():
    # parse input
    N, K = map(int, input().split())
    PS = list(map(int, input().split()))
    CS = list(map(int, input().split()))
    print(solve(N, K, PS, CS))


# tests
T1 = """
5 2
2 4 5 1 3
3 4 -10 -8 8
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
8
"""

T2 = """
2 3
2 1
10 -7
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
13
"""

T3 = """
3 3
3 1 2
-1000 -2000 -3000
"""
TEST_T3 = """
>>> as_input(T3)
>>> main()
-1000
"""

T4 = """
10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719
"""
TEST_T4 = """
>>> as_input(T4)
>>> main()
29507023469
"""

T5 = """
2 3

"""
TEST_T5 = """
>>> as_input(T5)
>>> main()
result
"""


def _test():
    import doctest
    doctest.testmod()
    g = globals()
    for k in sorted(g):
        if k.startswith("TEST_"):
            doctest.run_docstring_examples(g[k], g)


def as_input(s):
    "use in test, use given string as input file"
    import io
    f = io.StringIO(s.strip())
    g = globals()
    g["input"] = lambda: bytes(f.readline(), "ascii")
    g["read"] = lambda: bytes(f.read(), "ascii")


input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read

if sys.argv[-1] == "-t":
    print("testing")
    _test()
    sys.exit()

main()

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

max_score = -10**22
for i in range(N):
  score = 0
  count = 0
  j = i
  n = 0
  for _ in range(N):
    j = P[j]-1
    count += C[j]
    n += 1
    if j == i:
      break
  k = K%n
  score = (K//n)*count
  if score < 0:
    score = 0
    if k == 0:
      k = N
  max_v = -10**22
  v = 0
  for _ in range(k):
    j = P[j]-1
    v += C[j]
    max_v = max(max_v, v)
  max_score = max(max_score, score+max_v)

print(max_score)

Submission status: Wrong Answer

Solution code:
def intex(sen):
    return int(sen)-1

n,k=map(int,input().split())
p=list(map(intex,input().split()))
c=list(map(int,input().split()))

anss = 0


for i in range(n):
    junkan = 1
    junkan_lst =[p[i]]
    next = p[i]
    while p[next] not in junkan_lst:
        junkan_lst.append(p[next])
        junkan += 1
        next = p[next]
    print(junkan)
    print(junkan_lst)
    ans = 0
    score_lst = [0]*junkan
    for k, j in enumerate(junkan_lst):
        score_lst[k] = (c[j])
    summ = sum(score_lst)

    if junkan >= k:
        lst = score_lst[:k]
        ans = max(lst)
    else:
        if summ <= 0:
            ans = max
        else:
            use = k//junkan
            amari = k%junkan
            score = []
            for j in score_lst:
                score.append(j+use*summ)
            for j in score_lst[:amari]:
                score.append(j+(use+1)*summ)
            ans = max(score)
    anss = max(anss,ans)
print(anss)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2147483647)
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))

# ループを見つける(5000), 一周のスコアを確認
is_visit = [0 for _ in range(n)]
loop = []

def search(i, j):
    if is_visit[i] == 0:
        is_visit[i] = j
        l.append(i)
        search(p[i]-1, j)
    else:
        pass

loop_id = 1
for i in range(n):
    l = []
    search(i, loop_id)
    if len(l) != 0:
        loop.append(l)
        loop_id += 1
# print(loop)
# print(is_visit)
s_list = [0 for _ in range(len(loop))]
for i in range(len(s_list)):
    l = loop[i]
    s = 0
    for j in range(len(l)):
        s += c[l[j]]
    s_list[i] = s

ans = [0 for _ in range(n)]
for i in range(n):
    # i からはじめて最大スコア
    l = loop[is_visit[i]-1] # 所属するループ
    tmp1 = 0 # ループによるスコア
    tmp_k = k
    s = s_list[is_visit[i]-1]
    if s > 0 and k > len(l):
        # 回るほどお得で一周より回れる
        tmp1 += s*(tmp_k//len(l)-1)
        tmp_k -= (tmp_k//len(l)-1)*len(l)
    elif s <= 0:
        tmp_k -= (tmp_k//len(l))*len(l)
        if tmp_k == 0:
            tmp_k = 2*len(l)
    pointer = p[i]
    tmp2 = [c[pointer-1] for _ in range(tmp_k)] # 愚直に進んだ点数
    if tmp_k != 0:
        for j in range(1, tmp_k):
            # k回目までの累積和で最大を求める
            pointer = p[pointer-1]
            tmp2[j] = tmp2[j-1] + c[pointer-1]
    # print(i, l, s, tmp_k, tmp1, tmp2)
    if len(tmp2) != 0:
        ans[i] = tmp1 + max(tmp2)
    else:
        ans[i] = tmp1
# print(ans)
print(max(ans))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int , input().split()))
c = list(map(int , input().split()))
ans = max(c)

x = [0] * n
t = list(range(1,n+1))

for j in range(min(k, 10000)):
    for i in range(n):
        x[i] += c[t[i]-1]
        t[i] = p[t[i]-1]
        ans = max(ans, x[i])

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
r = []
visit = [0] * n
for i in range(n):
    if not visit[i]:
        x = []
        j = i
        while True:
            if visit[j]:
                break
            x.append(c[j])
            visit[j] = 1
            j = p[j] - 1
        r.append(x)
l = len(r)
ans = -1145141919810
for x in r:
    ll = len(x)
    y = [0] * (ll + 1)
    for i in range(ll):
        y[i + 1] = y[i] + x[i]
    sumx = y[ll]
    a = 0
    b = -1145141919810
    kk = k
    #print(kk, ll)
    if ll < kk:
        if sumx > 0:
            a = (kk // ll) * sumx
        kk -= ll * (kk // ll)
        #b = 0
    #print(a, kk, ll, sumx)
    #print(y)
    kk = max(kk, 1)
    for i in range(1, kk + 1):
        for j in range(ll + 1 - i):
            #print(i + j, j)
            b = max(y[i + j] - y[j], b)
    for i in range(kk - 1):
        for j in range(i + 1):
            #print(ll - 1 - (j - 1), 1 + (i - j))
            b = max(y[ll] - (y[ll - 2 - (j - 1)] - y[1 + (i - j)]), b)
    ans = max(a + b, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

N, K = map(int, sys.stdin.readline().split())
P = list(map(int, sys.stdin.readline().split()))
C = list(map(int, sys.stdin.readline().split()))

# 重み付き有効グラフ
edges = [[] for _ in range(N)]
for i in range(N):
    edges[i].append((P[i]-1, C[i]))

# DFSで閉路と経路の最大取得スコアを調査
max_path_score = -float("inf")
cycle = set() # (score, count, start_node)
for i in range(N):
    visited = set()
    q = deque([(i, 0, 0)])
    while q:
        node1, score, count = q.popleft()
        if K < count:
            continue
        if 0 < count: 
            max_path_score = max(max_path_score, score)
        if node1 in visited:
            # 閉路
            if score > 0:
                cycle.add((score, count, i))
            continue
        visited.add(node1)
        for node2, weight in edges[node1]:
            q.appendleft((node2, score + weight, count + 1))
# print("max_path", max_path_score)

if len(cycle) == 0:
    print(max_path_score)
else:
    ans = max_path_score

    # サイクル内のノードは一回だけ計算する
    calculated = set()
    # サイクルごとの最大スコアを算出
    for (score, length, start) in cycle:
        path_list = []
        q = deque([start])
        visited = set()
        while q:
            node = q.popleft()
            path_list.append((node, C[node]))
            if node in visited:
                break
            visited.add(node)
            for node2, weight in edges[node]:
                q.append(node2)

        # サイクルのパス内で得られる最大スコア
        acum = [0 for _ in range(len(path_list) + 1)] # 累積和
        for i, (node, weight) in enumerate(path_list):
            calculated.add(node)
            acum[i+1] = acum[i] + weight
        path_max = -float("inf")
        res_path_max = - float("inf") # サイクルのあまりで到達できる最大スコア
        res_len = K % length
        for i in range(len(path_list)):
            for j in range(i, len(path_list) + 1):
                tmp_score = acum[j] - acum[i]
                path_max = max(path_max, tmp_score)
                if j - i <= res_len:
                    res_path_max = max(res_path_max, tmp_score)
                    
        
        # あまりを使う場合
        ans = max(ans, score * (K // length) + res_path_max)    
        # サイクル内の最大パスを使う場合
        ans = max(ans, score * (K // length - 1) + path_max)

    print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
p = [0] + p
c = list(map(int, input().split()))
c = [0] + c
score = [[0] * (n + 1) for _ in range(n + 1)]
l_cycle = [0] * (n + 1)
for i in range(1, n + 1):
    start = i
    move_cnt = 0
    nxt = i
    while move_cnt < n:
        nxt = p[nxt]
        score[i][move_cnt + 1] += score[i][move_cnt] + c[nxt]
        move_cnt += 1
        if nxt == start:
            l_cycle[start] = move_cnt
            break
# for i in range(1, n + 1):
#     print(score[i])
# print('l_cycle', l_cycle)
ans = -float('inf')
for s in range(1, n + 1):
    sk = k // l_cycle[s]
    arieru = score[s][1:l_cycle[s] + 2]
    temp = max(score[s][1:l_cycle[s] + 2])

    # print(f's={s}')
    # print(f'sk={sk}')
    # print('start:', s)
    # print('arieru', arieru)
    # print(temp, s)
    ans = max(ans, temp)
    temp += sk * score[s][l_cycle[s]]
    ans = max(ans, temp)
    # print('ans:', ans)
print(ans)

Submission status: Wrong Answer

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

p.insert(0,0)
c.insert(0,0)
ans = -10**9
for i in range(1,n+1):
    visited = [0 for _ in range(n+1)]
    tmp = i
    tmp_ans = 0
    cnt = 0
    while cnt <= k:
        nxt = p[tmp]
        if visited[nxt] == 0:
            visited[nxt] = 1
            tmp_ans += c[nxt]
        else:
            if tmp_ans >= 0:
                tmp_ans += tmp_ans*((k-cnt)//cnt)#何周かできるなら
                ans = max(ans,tmp_ans)
                for j in range(k%cnt):#端数分
                    tmp_ans += c[nxt]
                    nxt = p[nxt]      
                    ans = max(ans,tmp_ans)              
            break
        ans = max(ans,tmp_ans)
        cnt += 1
        tmp = nxt

print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
import sys

input = sys.stdin.buffer.readline

n, k = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

kouho = []

used = [False] * (n)
for i in range(n):
    if used[i]:
        continue
    now = i
    cnt = 0
    res = 0
    route = []
    while True:
        if used[now]:
            break
        route.append(C[P[now] - 1])
        used[now] = True
        nex = P[now] - 1
        cnt += 1
        res += C[nex]
        now = nex
    kouho.append((res, cnt, route))

ans = -(10 ** 20)
for res, cnt, route in kouho:
    temp1 = 0
    num = len(route)
    if k >= cnt:
        if res > 0:
            temp1 += res * (k // cnt)
            cnt = k % cnt
        else:
            cnt = num
    else:
        cnt = k
    temp2 = -(10 ** 20)
    route += route
    ACR = list(accumulate([0] + route))
    for i in range(num):
        for j in range(1, cnt + 1):
            temp3 = ACR[j + i] - ACR[i]
            temp2 = max(temp2, temp3)
            # print((i, j), temp3)
    # print(temp1)
    ans = max(ans, temp1 + temp2)
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    N,K = list(map(int,input().split()))
    P = list(map(int,input().split()))
    P.insert(0,0)
    C = list(map(int,input().split()))
    C.insert(0,0)

    ans = -10**9
    loops = {}
    if 5000 < K:
        for i in range(1,N+1):
            p = i
            k = K
            max_score = -10**9
            score = 0
            visited = set([p])
            visited_lst = [p]
            score_lst = [0]
            while 0 < k:
                score += C[P[p]]
                max_score = max(max_score,score)
                score_lst.append(score)
                p = P[p]
                k -= 1
                if p in visited:
                    if p in loops:
                        if 0 < loops[p][0]:
                            score += loops[p][0]*(k//loops[p][1])
                            k %= loops[p][1]
                            visited = set([p])
                            visited_lst = [p]
                            score_lst = [score]
                        else:
                            break
                    else:
                        idx = visited_lst.index(p)
                        l = len(score_lst)-1-idx
                        for j in range(idx,l):
                            loops[visited_lst[j]] = [score-score_lst[idx],l]
                        if 0 < score-score_lst[idx]:
                            score += (score-score_lst[idx])*(k//l)
                            k %= l
                            visited = set([p])
                            visited_lst = [p]
                            score_lst = [score]
                        else:
                            break
                else:
                    visited.add(p)
                    visited_lst.append(p)
            # print(max_score)
            max_score = max(max_score,score)
            ans = max(ans,max_score)
        # print(loops)
    else:
        for i in range(1,N+1):
            p = i
            k = K
            max_score = -10**9
            score = 0
            while 0 < k:
                score += C[P[p]]
                max_score = max(max_score,score)
                p = P[p]
                k -= 1
            ans = max(ans,max_score)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import math


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def solve():
    N, K = read_ints()
    P = [p-1 for p in read_ints()]
    C = read_ints()

    max_score = -math.inf
    for i in range(N):
        cycle_score = C[i]
        scores = [0, C[i]]
        j = P[i]
        k = K
        while k > 1 and i != j:
            cycle_score += C[j]
            scores.append(cycle_score)
            j = P[j]
            k -= 1
        cycle_size = len(scores)-1
        cycle_count = K//cycle_size
        if cycle_count != 0:
            max_score = max(max_score, max(scores[1:]), cycle_score*cycle_count+max(scores[:K%cycle_size+1]))
    return max_score


if __name__ == '__main__':
    print(solve())

Submission status: Wrong Answer

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

P = list(map(int,input().split()))

C = list(map(int,input().split()))

ans = -10000000000

if K <= N:
    for i in range(N):
        count = 0
        tmp_point = 0
        nv = i
        while count < K:
            nvv = P[nv]
            nvv -= 1
            tmp_point += C[nvv]
            count += 1
            nv = nvv
            ans = max(ans, tmp_point)
    print(ans)
else:
    loop = [0]*N
    for i in range(N):
        count = 0
        check = [False]*N
        tmp_point = 0
        nv = i
        while True:
            nvv = P[nv]
            nvv -= 1
            if check[nvv] == True:
                break
            check[nvv] = True
            tmp_point += C[nvv]
            count += 1
            nv = nvv
            ans = max(ans, tmp_point)
        loop[i] = [tmp_point, count, i]
    loop.sort(reverse=True)
    #print(loop)
    new_ans = -10000000
    for value, counter, key in loop:
        if value < 0:
            break
        shou = K//counter
        amari = K%counter
        tmp_ans = value*shou
        new_ans = max(new_ans, tmp_ans)
        count = 0
        nv = key
        while count < amari:
            nvv = P[nv]
            nvv -= 1
            tmp_ans += C[nvv]
            count += 1
            nv = nvv
            new_ans = max(new_ans, tmp_ans)
        
    #print(max(max(loop),ans , new_ans))
    print(max(loop[0][0], ans, new_ans))

Submission status: Wrong Answer

Solution code:
from sys import stdin
from math import inf
input=stdin.readline
n,k=map(int,input().split())
arr=[0]+list(map(int,input().split()))
cost=[0]+list(map(int,input().split()))
ma=-inf
for i in range(1,n+1):
    m=1
    cur=arr[i]
    co=cost[cur]
    l=[0,co]
    ma = max(ma, l[-1])
    while(m<k and cur!=i):
        cur=arr[cur]
        co=cost[cur]
        l.append(l[-1]+co)
        m += 1
        ma=max(ma,l[-1])
    if m<=k:
        for j in range(k%m+1):
            ma = max(ma, l[-1] * (k//m) + l[j])
print(ma)

'''
3 4
3 1 2
-1 3 -1
'''

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
ps = list(map(int, input().split()))
cs = list(map(int, input().split()))

score = 0

for c in cs:
	new_score = 0
	for _ in range(k):
		dest = ps[cs.index(c)]
		new_score += cs[dest-1]
		score = max(score, new_score)
		c = cs[dest-1]
	score = max(score, new_score)

print(score)

Submission status: Wrong Answer

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
n,k = ma()
Pt = lma()
P = [p-1 for p in Pt]
C = lma()
class unionfind():
    def __init__(self,n):
        self.par = list(range(n))
        self.size = [1]*n
        self.rank = [0]*n

    def root(self,x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.root(self.par[x])
            return self.par[x]

    def same(self,x,y):
        return self.root(x) == self.root(y)

    def unite(self,x,y):
        x = self.root(x)
        y = self.root(y)
        if x==y:return
        else:
            if self.rank[x] < self.rank[y]:
                 x,y = y,x
            if self.rank[x] == self.rank[y]:
                self.rank[x]+=1
            self.par[y] = x
            self.size[x] +=self.size[y]
    def get_size(self,x):
        x = self.root(x)
        return self.size[x]
uf = unionfind(n)
for i in range(n):
    uf.unite(i,P[i])

def score(x):#xからスタートしたスコア
    l = uf.get_size(x)
    p,r = divmod(k,l)
    tmp = [-10**10 for i in range(l+1)]#一回の累積和
    tmp_p = [-10**10 for i in range(l+1)] #pサイクル目の累積和
    ret = 0
    if p==0:
        xt=x
        mx = -10*18
        for i in range(r):
            nex = P[xt]
            ret+=C[nex]
            xt = nex
            mx = max(mx,ret)
        return mx

    gain_cycle = 0
    xt=x
    for i in range(l):
        nex = P[xt]
        gain_cycle +=C[nex]
        ret+=C[nex]
        tmp[i+1] = ret
        if i<=r-1:
            tmp_p[i+1]=ret
        xt = nex
    if gain_cycle>0:
        return max(tmp_p) + p* gain_cycle
    else:
        return max(tmp)

        #print(ret,"ret")

ans = -10**18
for i in range(n):
    ans = max(ans,score(i))
print(ans)

Submission status: Wrong Answer

Solution code:
def max_score(_l, n):
  _l = _l + _l
  if n == 0:
    return 0
  ans = -(10 ** 100)
  for i in range(1, len(_l) - 1):
    _l[i] += _l[i - 1]
  for i in range(len(_l) // 2):
    for j in range(1, min(n + 1, len(_l) - i)):
      ans = max(ans, _l[i + j] - _l[i])
  return ans

n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
check = [False for i in range(n)]

ans = -(10 ** 100)
for i in range(n):
  if check[i]:
    continue
  _i = i
  l = []
  while not check[_i]:
    check[_i] = True
    _i = p[_i] - 1
    l.append(c[_i])
  if k % len(l) != 0:
    _ans = k // len(l) * max(0, sum(l))
    _ans += max_score(l, k % len(l))
  else:
    _ans = (k // len(l) - 1) * max(0, sum(l))
    _ans += max_score(l, len(l))
  ans = max(ans, _ans)

print(ans)

Submission status: Wrong Answer

Solution code:
n,k=list(map(int, input().split()))
p=list(map(int, input().split()))
c=list(map(int, input().split()))
z=-10000000000000
lin=[0]*n
lstart=[]
llen=[]
loopsum=[]
loopstructure=[]
stsc=[]
for i in range(n):
    if lin[i]==0:
        lstart.append(i)
        d=i
        f=0
        v=0
        strc=[i]
        sc=[c[i]]
        while lin[d]==0:
            lin[d]=1
            d=p[d]-1
            strc.append(d)
            sc.append(c[d])
            f+=1
            v+=c[d]
            if i==d :
                llen.append(f)
                loopsum.append(v)
                loopstructure.append(strc)
                stsc.append(sc)                
for j in range(len(stsc)):
    o=len(stsc[j])-1
    x=-10000000000000
    y=-10000000000000
    p=min(o,k)
    for i in range(o):
        for ii in range(1,k+1):
            if i+ii<o:
                ny=sum(stsc[j][i:i+ii])
            else:
                ny=sum(stsc[j][0:i+ii-o]+stsc[j][i:o])
            if ny>y:
                y=ny

                
    nz=max((k//o)*loopsum[j]+y,y)
    if nz>z:
        z=nz
print(z)

Submission status: Wrong Answer

Solution code:
N,K = list(map(int,input().split()))
P = list(map(int,input().split()))
C = list(map(int,input().split()))

loopcheck = [0]*N
As = []
for i in range(N):
    if loopcheck[i]==0:
        now = i
        A = []
        while loopcheck[now]==0:
            loopcheck[now]=1
            A.append(C[P[now]-1])
            now = P[now]-1
        As.append(A)
out = -1*10**10
for A in As:
    SA = sum(A)
    NA = len(A)
    B = A + A
    T = min(NA,K)
    outtmp = max(A)
    S = [0]
    kosu = 1
    for i in range(0,len(B)):
        S.append(S[-1]+B[i])
    for i in range(NA-1):
        for j in range(i+1,i+T):
            outtmp = max(outtmp,S[j]-S[i])
            if outtmp==S[j]-S[i]:
                kosu = j+1-i
    if SA>0:
        if kosu==NA:
            Y = K - (K//NA)*NA+1
            outtmpex = -10**10
            for i in range(NA-1):
                for j in range(i+1,i+Y):
                    outtmpex = max(outtmpex,S[j]-S[i])
            outtmp = SA*(K//NA)+outtmpex
        else:
            outtmp = outtmp+SA*((K-kosu)//NA)
    out = max(outtmp,out)
print(out)

Submission status: Wrong Answer

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")

n, k = map(int, input().split())
p = [int(x) - 1 for x in input().split()]
c = [int(x) for x in input().split()]

ans = -float('inf')
for i in range(n):
    now = i
    c_sum = [0]
    s = set()
    cnt = 0
    while True:
        s.add(now)
        c_sum.append(c_sum[-1] + c[now])
        cnt += 1
        now = p[now]
        if now in s:
            break
    c_sum = c_sum[1:]
    if k < cnt:
        ans = max(ans, max(c_sum[: k]))
    else:
        score = c_sum[-1]
        count = k // cnt
        k_ = k - count*cnt
        score *= count
        if k_ > 0:
            score += max(c_sum[:k_])
        ans = max(ans, score, max(c_sum))
print(ans)