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 = map(int,input().split())
p = list(map(int,input().split()))
c = list(map(int,input().split()))

ans = -float('inf')
for i in range(n):
    score = []
    check = [0] * n
    now = i
    cycle = 0
    for j in range(k):
        go = p[now] - 1
        if check[go] == 1:
            break
        now = go
        if j == 0:
            score.append(c[now])
        else:
            score.append(score[-1] + c[now])
        check[now] = 1
        cycle += 1

    t = k // cycle
    m = k % cycle

    if m == 0:
        ans = max(score[-1] * t, max(score), ans)
    else:
        ans = max(score[-1] * t + max(score[:m]), max(score), ans)

print(ans)

Submission status: Wrong Answer

Solution code:
N, K = [int(_) for _ in input().split()]
P = [int(_) - 1 for _ in input().split()]
C = [int(_) for _ in input().split()]


X = [False for _ in range(N)]

V = []
for i in range(N):
    if X[i]:
        continue
    t = i
    v = []
    while X[t] is False:
        X[t] = True
        v.append(C[t])
        t = P[t]
    V.append(tuple(v))

def f(v, K):
    if K == 0:
        return 0
    if max(v) < 0:
        return max(v)
    n = len(v)

    X = [0]
    for i in range(n):
        X.append(X[-1] + v[i])
    ans = -100000000000
    for i in range(n + 1):
        for j in range(i):
            if i - j > K:
                continue
            ans = max(ans, X[i] - X[j])
    return(ans)

ans = -100000000000
for v in V:
    n = len(v)
    if K > n:
        s = sum(v)
        if s > 0:
            a = s * (K // n) + f(v * 2, K % n) 
        else:
            a = f(v * 2, n)
    else:
        a = f(v * 2, K)
    ans = max(a, ans)

print(ans)

Submission status: Wrong Answer

Solution code:
N, K = [int(_) for _ in input().split()]
P = [int(_) - 1 for _ in input().split()]
C = [int(_) for _ in input().split()]


X = [False for _ in range(N)]

V = []
for i in range(N):
    if X[i]:
        continue
    t = i
    v = []
    while X[t] is False:
        X[t] = True
        v.append(C[t])
        t = P[t]
    V.append(tuple(v))

def f(v, K):
    if max(v) < 0:
        return max(v)
    n = len(v)

    X = [0]
    for i in range(n):
        X.append(X[-1] + v[i])
    ans = -100000000000
    for i in range(n + 1):
        for j in range(i):
            if i - j > K:
                continue
            ans = max(ans, X[i] - X[j])
    return(ans)

ans = -100000000000
for v in V:
    n = len(v)
    if K > n:
        s = sum(v)
        if s > 0:
            a = s * (K // n) + f(v * 2, K % n) 
        else:
            a = f(v * 2, n)
    else:
        a = f(v * 2, K)
    ans = max(a, ans)

print(ans)

Submission status: Wrong Answer

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

ans = -10**9-1
for i in range(N):
    seen = [-1]*N
    cumsum = [0]*(N+1)
    now = i
    j = 0
    while seen[now] == -1:
        seen[now] = 1
        now = P[now]
        cumsum[j+1] = cumsum[j] + C[now]
        j += 1
    loop_size = j
    if K <= loop_size:
        ans = max([ans] + cumsum[1:K+1])
    else:
        if cumsum[loop_size] > 0:
            loop_n = K//loop_size
            score = cumsum[loop_size]*loop_n + max(cumsum[0:K%loop_size+1])
            ans = max(ans, score)
        else:
            ans = max([ans] + cumsum[1:loop_size+1])
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()))

check=[0]*n
group=[]

for i in range(n):
    tmp=i
    if check[tmp]==0:
        tmp_group=[]
        while check[tmp]==0:
            tmp_group.append(tmp)
            check[tmp]=1
            tmp=p[tmp]-1

        group.append(tmp_group)

ans="start"

#startの最低とgoalの最高の和
for item in group:
    
    #一周すると何になるか。これはどこスタートでも同じ
    circle=0
    cnt=k
    if len(item)<k:
        for v in item:
            circle+=c[v]
        circle=circle*(k//len(item))
        cnt=k%len(item)
    
    #一周した後のあまりで最強を探す

    goal=(-1)*(10**18)
    
    #startは各groupのindexが入ってる
    for start in range(len(item)):
        tmp=0
        #print("start",item,start,cnt)
        for i in range(start,start+cnt):
            #print(">>",i)
            tmp+=c[item[i%len(item)]]
            #print(item[i%len(item)],c[item[i%len(item)]])
            goal=max(goal,tmp)

    #print(item,circle,goal)
    if ans=="start":
        ans=goal+max(0,circle)
    else:
        ans=max(ans,goal+max(0,circle))

    if circle<=0 and len(item)<=k:
        for i in range(len(item)):
            tmp_ans=c[item[i]]
            for j in range(1,len(item)):
                tmp_ans+=c[item[(i+j)%len(item)]]
                ans=max(ans,tmp_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()))

check=[0]*n
group=[]

for i in range(n):
    tmp=i
    if check[tmp]==0:
        tmp_group=[]
        while check[tmp]==0:
            tmp_group.append(tmp)
            check[tmp]=1
            tmp=p[tmp]-1

        group.append(tmp_group)

ans="start"

#startの最低とgoalの最高の和
for item in group:
    
    #一周すると何になるか。これはどこスタートでも同じ
    circle=0
    cnt=k
    if len(item)<k:
        for v in item:
            circle+=c[v]
        circle=circle*(k//len(item))
        cnt=k%len(item)
    
    #一周した後のあまりで最強を探す

    goal=(-1)*(10**18)
    
    #startは各groupのindexが入ってる
    for start in range(len(item)):
        tmp=0
        #print("start",item,start,cnt)
        for i in range(start,start+cnt):
            #print(">>",i)
            tmp+=c[item[i%len(item)]]
            #print(item[i%len(item)],c[item[i%len(item)]])
            goal=max(goal,tmp)

    #print(item,circle,goal)
    if ans=="start":
        ans=goal+max(0,circle)
    else:
        ans=max(ans,goal+max(0,circle))

    if circle<0 and len(item)<k:
        for i in range(len(item)):
            tmp_ans=c[item[i]]
            for j in range(1,len(item)):
                tmp_ans+=c[item[(i+j)%len(item)]]
                ans=max(ans,tmp_ans)




print(ans)

Submission status: Wrong Answer

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

import copy

ps = list(map(int, input().split()))
cs = list(map(int, input().split()))

graphs = []
vGraphs = []
flags = [False]*n
for i in range(len(ps)):
    p = ps[i]
    index = p - 1
    if flags[index]:
        continue

    current = []
    values = []
    currentIndex = index
    while True:
        if flags[currentIndex]:
            break
        current.append(currentIndex)
        values.append(cs[currentIndex])
        flags[currentIndex] = True
        nextIndex = ps[currentIndex] - 1
        currentIndex = nextIndex
    graphs.append(current)
    vGraphs.append(values)

import itertools

accus = []
for g in vGraphs:
    g_g = [0] + g*2
    l = list(itertools.accumulate(g_g))
    accus.append(l[:len(l)-1])

maxLen = 0

maxV = -float('inf')
for ac in accus:
    for i in range(len(ac)):
        baseV = ac[i]
        searchRange = k
        for r in range(i+1, min(i + 1 + searchRange, len(ac))):
            multiV = 0
            currentLoopLen = (len(ac)) // 2
            if (r - i) >= currentLoopLen:
                len_ = k // currentLoopLen - 1
                if (r - i) % currentLoopLen > k % currentLoopLen:
                    len_ -= 1
                loopNum = (max(0, len_))
                multiV = (ac[currentLoopLen + i] - baseV) * loopNum

            sumV = ac[r] - baseV + multiV
            # if sumV > maxV:
            #     print()
            maxV = max(maxV, sumV)


print(maxV)

Submission status: Wrong Answer

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

visited=[True for _ in range(N)]
tempv=[]
sets=[]
if sum(1 for i in C if i<=0)==N:
    print(max(C))
    exit()
i=0
total=0
while True:
    if visited[i]:
        visited[i]=False
        tempv.append(i)
        i=P[i]-1
        total+=1
    elif total==N:
        sets.append(tempv)
        tempv=[]
        break
    else:
        sets.append(tempv)
        tempv=[]
        for k in range(N):
            if visited[k]:
                i=k
                break


# print(sets)
nofsets=len(sets)
ans=0
temp=0
for i in range(nofsets):
    tempv=[C[j] for j in sets[i]]
    if K>len(tempv):
        oneset=sum(tempv)
        if oneset>0:
            temp=K//len(tempv)
            remain=K%len(tempv)
            dtempv=tempv+tempv
            rnax=0
            for s in range(len(tempv)):
                rman=sum([dtempv[s+j] for j in range(remain)])
                rnax=max(rnax,rman)
            tempa=rnax+temp*oneset
            ans=max(ans,tempa)
    for s in range(len(tempv)):
        dtempv=tempv+tempv
        for j in range(len(tempv)):
            temp=sum([dtempv[s+k]for k in range(j)])
            ans=max(ans,temp)

print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split()) # 2 ≤ N ≤ 5000  ; 1 ≤ K ≤ 10^9
P = list(map(int,input().split()))
C = list(map(int,input().split())) # −10^9 ≤ C[i] ≤ 10^9

ring_P = []

def get_score(CC):
    score_min = K * -10**9
    #score = [0] * K
    lenCC = len(CC)
    score_sum = sum(CC)
    if score_sum > 0:
        max_score = score_sum * (K // lenCC)
        KK = K % lenCC
    else :
        max_score = 0
        KK = K
    max_score_0 = score_min
    for i in range(lenCC-1):
        for j in range(i+1,lenCC):
            score_0 = sum(CC[i:j]) 
            score_1 = score_sum - score_0
            if j-i > KK :
                score_0 = score_min
            if lenCC - ( j - i) > KK :
                score_1 = score_min
            max_score_0 = max(score_0, score_1, max_score_0)
    max_score = max( max_score_0 + max_score ,max_score)

    return max_score

max_score = K * -10**9
Arr = [0] * (N+1)
i = 1
while i < N+1:
    if Arr[i] != 1:
        CC = []
        Arr[i] = 1
        init = i
        i = P[i-1]
        CC.append(C[i-1])
        #print(i)
        while init != i:
            Arr[i] = 1
            i = P[i-1]
            #print(i)
            CC.append(C[i-1])

        #print(CC)
        #print([C[i-1] for i in PP])
        max_score = max(get_score(CC),max_score)
        #print(max_score)
    i += 1

print(max_score)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
D = list()
nlist = list(range(1,N+1))

ilist = list()

while len(nlist) > 0:
  i = nlist[0]
  l = list()
  while True:
    if i in ilist:
      D.append(l)
      break
    else:
      l.append(C[P[i-1] - 1])
      ilist.append(i)
      nlist.remove(i)
      i = P[i-1]

def culcmax(A):
  S = list()
  for i in range(len(A)):
    if i == 0:
      S.append(A[i])
    else:
      S.append(max(S[-1] + A[i], A[i]))
  return max(S)
ret = list()
for L in D:
  if K >= len(L):
    tmp_ret = list()
    for i in range(len(L)):
      l_ = L[:i].copy()
      tmp = L[i:].copy()
      l_.extend(tmp)
      tmp_ret.append(culcmax(l_))
    ret.append(max(tmp_ret))
  else:
    L_ = L.copy()
    L_.extend(L_)
    tmp_ret = list()
    for i in range(len(L)):
      l_ = L_[i:i+K]
      tmp_ret.append(culcmax(l_))
    ret.append(max(tmp_ret))
print(max(ret))

Submission status: Wrong Answer

Solution code:
N, K = [int(_) for _ in input().split()]
P = [int(_) - 1 for _ in input().split()]
C = [int(_) for _ in input().split()]


X = [False for _ in range(N)]

V = []
for i in range(N):
    if X[i]:
        continue
    t = i
    v = []
    while X[t] is False:
        X[t] = True
        v.append(C[t])
        t = P[t]
    V.append(tuple(v))

def f(v, K):
    if max(v) < 0:
        return max(v)
    n = len(v)

    X = [v[0]]
    for i in range(1, n):
        X.append(X[-1] + v[i])
    ans = -100000000000
    for i in range(n):
        for j in range(i):
            if i - j > K:
                continue
            ans = max(ans, X[i] - X[j])
    return(ans)

ans = -100000000000
for v in V:
    n = len(v)
    if K > n:
        s = sum(v)
        if s > 0:
            a = s * (K // n) + f(v * 2, K % n) 
        else:
            a = f(v * 2, n)
    else:
        a = f(v * 2, K)
    ans = max(a, 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()))

ans = -float('inf')
for i in range(n):
    now = i
    score = []
    check = [0] * n
    cnt = 0
    for j in range(k):
        go = p[now] - 1
        if check[go] == 1:
            break
        now = go
        if j == 0:
            score.append(c[now])
        else:
            score.append(score[j-1] + c[now])
        check[now] = 1
        cnt += 1
    d = k // cnt
    e = k % cnt
    if e == 0:
        ans = max(score[-1] * d, max(score), ans)
    else:
        ans = max(score[-1] * d + max(score[:e]), max(score), 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()))

check=[0]*n
group=[]

for i in range(n):
    tmp=i
    if check[tmp]==0:
        tmp_group=[]
        while check[tmp]==0:
            tmp_group.append(tmp)
            check[tmp]=1
            tmp=p[tmp]-1

        group.append(tmp_group)

ans="start"

#startの最低とgoalの最高の和
for item in group:
    
    #一周すると何になるか。これはどこスタートでも同じ
    circle=0
    cnt=k
    if len(item)<k:
        for v in item:
            circle+=c[v]
        circle=circle*(k//len(item))
        cnt=k%len(item)
    
    #一周した後のあまりで最強を探す


    goal=(-1)*(10**18)
    
    #startは各groupのindexが入ってる
    for start in range(len(item)):
        tmp=0
        #print("start",item,start,cnt)
        for i in range(start,start+cnt):
            #print(">>",i)
            tmp+=c[item[i%len(item)]]
            #print(item[i%len(item)],c[item[i%len(item)]])
            goal=max(goal,tmp)

    #print(item,circle,goal)
    if ans=="start":
        ans=goal+max(0,circle)
    else:
        ans=max(ans,goal+max(0,circle))

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()))

check=[0]*n
group=[]

for i in range(n):
    tmp=i
    if check[tmp]==0:
        tmp_group=[]
        while check[tmp]==0:
            tmp_group.append(tmp)
            check[tmp]=1
            tmp=p[tmp]-1

        group.append(tmp_group)

ans="start"

#startの最低とgoalの最高の和
for item in group:
    
    #一周すると何になるか。これはどこスタートでも同じ
    circle=0
    cnt=k
    if len(item)<k:
        for v in item:
            circle+=c[v]
        circle=circle*(k//len(item))
        circle=max(circle,0)    
        cnt=k%len(item)
    
    #一周した後のあまりで最強を探す


    goal=(-1)*(10**18)
    
    #startは各groupのindexが入ってる
    for start in range(len(item)):
        tmp=0
        #print("start",item,start,cnt)
        for i in range(start,start+cnt):
            #print(">>",i)
            tmp+=c[item[i%len(item)]]
            #print(item[i%len(item)],c[item[i%len(item)]])
            goal=max(goal,tmp)

    #print(item,circle,goal)
    if ans=="start":
        ans=goal+max(0,circle)
    else:
        ans=max(ans,goal+max(0,circle))

print(ans)

Submission status: Wrong Answer

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

import copy
p_list = [[0 for _ in range(n)] for _ in range(n)]
position = [[-1 for _ in range(n)] for _ in range(n)]
shuki = [-1 for _ in range(n)]
for i in range(n):
    p_list[0][i] += c[p[i]]
    position[0][i] = p[i]    
for i in range(1, n):
    for j in range(n):
        position[i][j] = p[position[i - 1][j]]
        p_list[i][j] = p_list[i - 1][j] + c[position[i][j]]        
        if (position[i][j] == j) & (shuki[j] == -1):
            shuki[j] = i + 1
ans = max(c)
for i in range(n):
    v = 0
    if shuki[i] >= 0:
        if p_list[shuki[i] - 1][i] > 0:
            v += p_list[shuki[i] - 1][i] * (k // shuki[i])
            if k % shuki[i] > 0:
                tmp_list = [p_list[j][i] for j in range(len(p_list))][:(k%shuki[i])]
                v += max(tmp_list)
        else:
            v += max([p_list[j][i] for j in range(len(p_list))][:k])
    else:
        v += max([p_list[j][i] for j in range(len(p_list))][:k])
    ans = max(v, ans)
print(ans)

Submission status: Wrong Answer

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

import copy
p_list = [[0 for _ in range(n)] for _ in range(n)]
position = [[-1 for _ in range(n)] for _ in range(n)]
shuki = [-1 for _ in range(n)]
for i in range(n):
    p_list[0][i] += c[p[i]]
    position[0][i] = p[i]    
for i in range(1, n):
    for j in range(n):
        position[i][j] = p[position[i - 1][j]]
        p_list[i][j] = p_list[i - 1][j] + c[position[i][j]]        
        if (position[i][j] == j) & (shuki[j] == -1):
            shuki[j] = i + 1
ans = -(10 ** 18)

for i in range(n):
    v = 0
    if shuki[i] >= 0:
        if p_list[shuki[i] - 1][i] > 0:
            v += p_list[shuki[i] - 1][i] * (k // shuki[i])
            if k % shuki[i] > 0:
                tmp_list = [p_list[j][i] for j in range(len(p_list))][:(k%shuki[i])]
                v += max(tmp_list)
        else:
            v += max([p_list[j][i] for j in range(len(p_list))][:k])
    else:
        v += max([p_list[j][i] for j in range(len(p_list))][:k])
    if v != 0:
        ans = max(v, 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()))

if n >= k:
    ans = -float('inf')
    for i in range(n):
        now = i
        score = []
        for j in range(k):
            now = p[now] - 1
            if j == 0:
                score.append(c[now])
            else:
                score.append(score[j-1] + c[now])
        ans = max(max(score), ans)
else:
    ans = -float('inf')
    for i in range(n):
        now = i
        score = []
        check = [0] * n
        cnt = 0
        for j in range(k):
            go = p[now] - 1
            if check[go] == 1:
                break
            now = go
            if j == 0:
                score.append(c[now])
            else:
                score.append(score[j-1] + c[now])
            check[now] = 1
            cnt += 1
        d = k // cnt
        e = k % cnt
        if e == 0:
            ans = max(score[-1] * d, max(score), ans)
        else:
            ans = max(score[-1] * d + max(score[:e]), max(score), ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        su = sum(s)
        div, mod = divmod(k, le)
        if su < 0 and k >= le:
            tmp = su
            for i in range(le):
                tmp_3 = 0
                for j in range(le):
                    p = (i + j) % le
                    tmp_3 += s[p]
                    if tmp_3 > tmp:
                        tmp = tmp_3
        else:
            tmp = div * su
            tmp_5 = - float('Inf')
            for i in range(le):
                tmp_4 = 0
                for j in range(mod):
                    p = (i + j) % le
                    tmp_4 += s[p]
                    if tmp_4 > tmp_5:
                        tmp_5 = tmp_4
            if k >= le:
                tmp = max(tmp + tmp_5, tmp)
            else:
                tmp = tmp_5

        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        su = sum(s)
        div, mod = divmod(k, le)
        if su < 0 and k >= le:
            tmp = su
            for i in range(le):
                tmp_3 = 0
                for j in range(le):
                    p = (i + j) % le
                    tmp_3 += s[p]
                    if tmp_3 > tmp:
                        tmp = tmp_3
        else:
            if k >= le:
                tmp = div * su
            else:
                tmp = - float('Inf')
            tmp_5 = - float('Inf')
            for i in range(le):
                tmp_4 = 0
                for j in range(mod):
                    p = (i + j) % le
                    tmp_4 += s[p]
                    if tmp_4 > tmp_5:
                        tmp_5 = tmp_4
            tmp = max(tmp + tmp_5, tmp)

        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        su = sum(s)
        div, mod = divmod(k, le)
        if su < 0 and k >= le:
            tmp = su
            for i in range(le):
                tmp_3 = 0
                for j in range(le):
                    p = (i + j) % le
                    tmp_3 += s[p]
                    if tmp_3 > tmp:
                        tmp = tmp_3
        else:
            tmp = div * su
            tmp_5 = - float('Inf')
            for i in range(le):
                tmp_4 = 0
                for j in range(mod):
                    p = (i + j) % le
                    tmp_4 += s[p]
                    if tmp_4 > tmp_5:
                        tmp_5 = tmp_4
            tmp = max(tmp + tmp_5, tmp)

        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    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()))

if n >= k:
    ans = -float('inf')
    for i in range(n):
        now = i
        score = [-float('inf')]
        for j in range(k):
            now = p[now] - 1
            if j == 0:
                score.append(c[now])
            else:
                score.append(score[j] + c[now])
        ans = max(max(score), ans)
    print(ans)
else:
    ans = -float('inf')
    for i in range(n):
        now = i
        score = [-float('inf')]
        check = [0] * n
        for j in range(k):
            go = p[now] - 1
            if check[go] == 1:
                break
            now = go
            if j == 0:
                score.append(c[now])
            else:
                score.append(score[j] + c[now])
            check[now] = 1
        d = k % j
        t = k // j
        score_2 = [-float('inf')]
        for j in range(d):
            now = p[now] - 1
            if j == 0:
                score_2.append(c[now])
            else:
                score_2.append(score_2[j] + c[now])
        res = max(score)
        res_2 = score[-1] * t + max(score_2)
        ans = max(ans, res, res_2)

    print(ans)

Submission status: Wrong Answer

Solution code:
import sys


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        su = sum(s)
        if k >= le:
            div, mod = divmod(k, le)
            if su < 0:
                tmp = su
                for i in range(le):
                    tmp_3 = 0
                    for j in range(le):
                        p = (i + j) % le
                        tmp_3 += s[p]
                        if tmp_3 > tmp:
                            tmp = tmp_3
            else:
                tmp = div * su
                tmp_5 = - float('Inf')
                for i in range(le):
                    tmp_4 = 0
                    for j in range(mod):
                        p = (i + j) % le
                        tmp_4 += s[p]
                        if tmp_4 > tmp_5:
                            tmp_5 = tmp_4
                tmp = max(tmp + tmp_5, tmp)
            # tmp = max(tmp_1, tmp_2)

        else:
            for i in range(le):
                tmp_1 = 0
                for j in range(k):
                    p = (i + j) % le
                    tmp_1 += s[p]
                    if tmp_1 > tmp:
                        tmp = tmp_1

        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
p = list(int(x)-1 for x in input().split())
c = list(map(int, input().split()))
score = -10**9
loop = [[] for _ in range(n+1)]
group = [0]*n
while 0 in group:
  i = group.index(0)
  here = i
  while group[i]==0:
    here = p[here]
    loop[i+1].append(here+1)
    group[here] = i+1
while [] in loop:
  loop.remove([])
for i in loop:
  s = [0]
  cc = []
  for j in i:
    s.append(s[-1]+c[j-1])
    cc.append(c[j-1])
  s.remove(0)
  l = k%len(s)
  resd = -10**9-1
  cc = cc + cc[:-1]
  if l!=0:
    for j in range(len(s)):
      resd = max(sum(cc[j:j+l]),resd)
  if s[-1]>0 and len(s)<k:
    sc = s[-1]*(k//len(s))+resd
  else:
    sc = max(resd,max(cc))
  score = max(sc,score)
print(score)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
a=-10**20
for i in range(n):
    l=[]
    j=p[i]-1
    l+=[c[p[i]-1]]
    while j!=i:
        l+=[l[-1]+c[p[j]-1]]
        j=p[j]-1
    if len(l)>=k:
        b=max(l[:k])
    else:
        z=l[-1]
        if z<0:
            b=max(l)
        else:
            q=len(l)
            if k%q==0:
                b=z*(k//q)
            else:
                b=z*(k//q)+max(l[:k%q])
    if a<b:
        a=b
print(a)