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:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
from itertools import accumulate #list(accumulate(A))

N, K = mi()
P = li()
C = li()
ans = -float('inf')

for i in range(N):
    score = 0
    ind = i
    his = []
    while True:
        ind = P[ind] - 1
        his.append(C[ind])
        if ind == i:
            #print(his)
            his = list(accumulate(his))
            L = len(his)
            if K > L:
                if his[-1] >= 0:
                    if not K%L:
                        ans = max(ans, his[-1] * (K//L))
                    else:
                        ans = max(ans, max(his[:K%L]) + his[-1] * (K//L))
                else:
                    ans = max(ans, max(his))
            else:
                ans = max(ans, max(his))
            break

print(ans)

Submission status: Wrong Answer

Solution code:
def solve():
    N, K = map(int, input().split(" "))
    _next = list(map(int, input().split(" ")))
    score = list(map(int, input().split(" ")))
    
    res = 0 
    if K > N :
        v = sum(score)
        if (K%N == 0) :
            res = v*((K//N)-1)
            K = N 
        else :
            res = v*((K//N))
            K = K % N
        res = max(res, 0)
    
    r = -float('inf')
    for i in range(N) :
        k = 0
        _res = 0
        at = i
        while k < K : 
            at = _next[at]-1
            _res += score[at]
            r = max(_res, r)
            k += 1
    return res+r

print(solve())

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(1000000)

def func(x):
    return x - 1

def main():
    N, K = map(int, input().split())
    P = list(map(func,map(int, input().split())))
    C = list(map(int, input().split()))
    flag = False
    for i in range(N):
        if C[i] >= 0:
            flag = True
    if not flag:
        print(max(C))
        exit()
    cand = []
    visited = [False] * N
    for i in range(N):
        if not visited[i]:
            Q = deque([i])
            tmp = [C[i]]
            while Q:
                x = Q.pop()
                visited[x] = True
                v = P[x]
                if not visited[v]:
                    Q.append(v)
                    tmp.append(C[v])
            cand.append(tmp+tmp)
    ans = 0
    for item in cand:
        tmp_score = 0
        S = sum(item) // 2
        L = len(item) // 2
        if S > 0:
            cnt = K % L
            for l in range(L):
                tmp = 0
                for j in range(cnt):
                    if item[l+j] >= 0:
                        tmp += item[l+j]
                        tmp_score = max(tmp_score, tmp)
                    else:
                        tmp = 0
            tmp_score += (K // L) * S
            ans = max(ans, tmp_score)
        else:
            cnt = min(K,L)
            for l in range(L):
                tmp = 0
                for j in range(cnt):
                    if item[l+j] >= 0:
                        tmp += item[l+j]
                        tmp_score = max(tmp_score, tmp)
                    else:
                        tmp = 0
            ans = max(ans, tmp_score)

    print(ans)
            




if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

N, K = map(int, input().split())
P = list(map(lambda x: int(x) - 1, input().split()))
C = list(map(int, input().split()))
ans = -float('inf')
for s in range(N):
    c = 0
    i = P[s]
    score = C[i]
    ans = max(ans, score)
    c += 1
    while i != s:
        i = P[i]
        score += C[i]
        ans = max(ans, score)
        c += 1
    cycle_len = c
    cycle_score = score
    q, r = divmod(K, cycle_len)
    score *= q
    if q:
        ans = max(ans, score)
    if r == 0:
        continue
    c = 0
    i = P[s]
    score += C[i]
    ans = max(ans, score)
    c += 1
    while c < r:
        i = P[i]
        score += C[i]
        c += 1
        ans = max(ans, score)
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):
    cnt = 0
    k = 0
    done = set()
    S = []
    while i not in done:
        done.add(i)
        ni = P[i] - 1
        if len(S):
            S.append(S[-1] + C[ni])
        else:
            S.append(C[ni])
        i = ni
    if K <= len(S):
        score = max(S[:K])
    elif S[-1] <= 0:
        score = max(S)
    else:
        score = S[-1] * (K // len(S))
        r = K % len(S)
        if r != 0:
            score += max(0, max(S[:r]))
    ans = max(ans, score)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = [int(n) for n in input().split(" ")]
Ps = [int(n) for n in input().split(" ")]
Cs = [int(n) for n in input().split(" ")]

#N = 10
#K = 58
#Ps = [9, 1, 6, 7, 8, 4, 3, 2, 10, 5]
#Cs = [695279662, 988782657, -119067776, 382975538, -151885171, -177220596, -169777795, 37619092, 389386780, 980092719]
"""
N = 3
K = 3
Ps = [3, 1, 2]
Cs = [-1000,-2000,-3000]
"""

circles = []
already = []
for p in range(N):
    if p not in already:
        tmp = []
        nowp = p
        while nowp not in tmp:
            tmp.append(nowp)
            nowp = Ps[nowp] - 1
        circles.append(tmp)
        for a in tmp:
            already.append(a)

#print(circles)

finalResult = -100000000000

def getCircleScore(circle, start, kk):
    #print(circle, start, kk)
    s = 0
    for k in range(kk):
        index = start + k
        if index >= len(circle):
            index = index % len(circle)
        s += Cs[circle[index]]
    return s


for circle in circles:
    
    CircleSum = sum([Cs[n] for n in circle])
    #print(circle, CircleSum)
    score = 0
    if CircleSum > 0:
        score = K // len(circle) * CircleSum

    K = K % len(circle)
    if K == 0:
        K = len(circle)

    maxScore = -100000000000
    for start in range(len(circle)):
        #print("start", start)
        for kk in range(1, K+1):
            s = getCircleScore(circle, start, kk)
            #print(s)
            if maxScore <= s:
                maxScore = s

    final = score + maxScore

    if final >= finalResult:
        finalResult = final

print(finalResult)

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n,k = na()
p = na()
c = na()

s = set(range(n))

ans = 0
loops = []
while s:
    loop = [0]
    a = s.pop()
    while True:
        loop.append(loop[-1]+c[p[a]-1])
        if p[a]-1 not in s:
            break
        a = p[a]-1
        s.discard(a)
    loops.append(loop[1:])
    
ans = 0
for tmp in loops:
    kk = min(k%len(tmp), k)
    loop = tmp+[tmp[-1]+u for u in tmp]
    x = 0
    for i in range(1,kk+1):
        for j in range(len(tmp)):
            x = max(x,loop[j+i]-loop[j])
    if k > len(tmp) and tmp[-1] > 0:
        x += tmp[-1]*(k//len(tmp))
    ans = max(ans,x)

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()))
l = []
check = [True]*n
for i in range(1,n+1):
    if (check[i-1]==True):
        s = i
        sl = []
        tnp = i
        for j in range(n):
            tnp = p[tnp-1]
            check[tnp-1] = False
            sl.append(c[tnp-1])
            if (tnp==s):
                break
        l.append(sl)
#print(l)
ans = -float("inf")
for i in range(len(l)):
    if (len(l[i])<=k):
        if (sum(l[i])>0):
            x = k%len(l[i])
            tnp = -float("inf")
            for p in range(1,x+1):
                wa = sum(l[i][:p])
                tnp = max(tnp,wa)
                for j in range(len(l[i])):
                    wa -= l[i][j]
                    wa += l[i][(j+p)%len(l[i])]
                    tnp = max(tnp,wa)
            ans = max(ans, tnp + sum(l[i])*(k//len(l[i])) )
        else:
            tnp = -float("inf")
            for p in range(1,len(l[i])):
                wa = sum(l[i][:p])
                tnp = max(tnp,wa)
                for j in range(len(l[i])):
                    wa -= l[i][j]
                    wa += l[i][(j+p)%len(l[i])]
                    tnp = max(tnp,wa)
            ans = max(ans, tnp)
    else:
        tnp = -float("inf")
        for p in range(1,k+1):
            wa = sum(l[i][:p])
            tnp = max(tnp,wa)
            for j in range(len(l[i])):
                wa -= l[i][j]
                wa += l[i][(j+p)%len(l[i])]
                tnp = max(tnp,wa)
        ans = max(ans, tnp)
print(ans)

Submission status: Wrong Answer

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

ret = -float('inf')
done = set()
for n in range(N) :
  if n in done :
    continue
    
  cur = n
  s = C[cur]
  done.add(cur)
  loop = [n]
  while not P[cur] in done :
    cur = P[cur]
    done.add(cur)
    loop.append(cur)
    s += C[cur]
  
  if s <= 0:
    for i in loop :
      cur = i
      x = 0
      for _ in range(min(N, K)) :
        cur = P[cur]
        x += C[cur]
        ret = max(ret, x)
  else :
    d = s * (K // len(loop))
    K %= len(loop)
      
    for i in loop :
      cur = i
      x = 0
      for _ in range(K) :
        cur = P[cur]
        x += C[cur]
        ret = max(ret, x + d)
      
print(ret)

Submission status: Wrong Answer

Solution code:

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

n, k = [int(i) for i in input().split()]
p = [int(i) for i in input().split()]
c = [int(i) for i in input().split()]

uf = UnionFind(n)
for i in range(n):
    uf.union(i,p[i]-1)

kotae = (-1) * 1000000001
for i in range(n):
    temp = 0
    if(uf.size(i) == 1):
        temp = c[i]
        temp = max(temp, temp * k)
    else:
        temp2 = i
        a = []
        temp3 = (-1) * 1000000001
        temp4 = 0
        temp5 = uf.size(i)
        for j in range(temp5):
            if(j == 0):
                a.append(c[p[temp2]-1])
            else:
                a.append(c[p[temp2] - 1]+a[j-1])
            temp2 = p[temp2]-1
            if(temp3 < a[j]):
                temp3 = a[j]
                temp4 = j
        temp = max(a)
        if(a[temp5-1] > 0):
            temp += ((k-temp4-1) // temp5) * a[temp5-1]

    kotae = max(kotae,temp)


print(kotae)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, K: int, P: "List[int]", C: "List[int]"):
    res = - 10 ** 10
    for i in range(N):
        lmax = - 10 ** 10
        nlmax = 0
        cp = P[i] - 1
        cl = 1
        cs = C[cp]
        while cp != i:
            if cs > lmax and cl <= K:
                lmax = cs
                nlmax = cl
            cp = P[cp] - 1
            cl += 1
            cs += C[cp]
        if cs > lmax and cl <= K:
            lmax = cs
            nlmax = cl
        syc = cs
        length = cl
        nloop = max(0, (K - nlmax) // length)
        res = max(res, max(lmax, syc * nloop + lmax))
        # print((i, syc, lmax, nlmax, length))
    print(res)
    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    P = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    C = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, K, P, C)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys

def II(): return int(input())
def MI(): return map(int,input().split())
def LI(): return list(map(int,input().split()))
def TI(): return tuple(map(int,input().split()))
def RN(N): return [input().strip() for i in range(N)]


def main():
    N, K = MI()
    P = LI()
    C = LI()
    
    ans_max = 0
    

    for i in range(N):
        NP = i
        sumN = 0
        j = 0
        while True:
                    
            NP = P[NP-1]
            a = P[NP-1]
            sumN += C[a-1]

            ans_max = max([ans_max, sumN])

            j += 1
            if j >= K:
                break

     

    
    print(ans_max)

if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
*p, = map(int, input().split())
p = [v - 1 for v in p]
*c, = map(int, input().split())
minc = min(c)

ans = minc


def get_loop(i):
    pos = i
    cnt = 0
    cur_score = 0
    max_score = minc
    while cnt == 0 or pos != i:
        pos = p[pos]
        cur_score = cur_score + c[pos]
        cnt += 1
        max_score = max(cur_score, max_score)
    return cnt, cur_score, max_score

# print(get_loop(2))

def solve(i, k):
    score = minc
    cur_score = 0
    pos = i
    loop_length, loop_score, max_loop_score = get_loop(i)
    if k // loop_length > 0 and loop_score > 0:
        # print("%s: %s // %s, %s, %s" % (i, k, loop_length, cur_score, max_loop_score))
        cur_score = loop_score * (k // loop_length)
        score = max(cur_score, score)
        score = max(cur_score, max_loop_score)
        k %= loop_length
    else:
        k = min(k, n)
    # print('rem k', k, "cur_score", cur_score)
    for _ in range(k):
        pos = p[pos]
        cur_score += c[pos]
        score = max(cur_score, score)
    # print("%s: %s" % (i, score))
    return score

for i in range(n):
    ans = max(ans, solve(i, k))
print(ans)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


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

    res = -f_inf
    for now in range(n):
        cnt = 0
        score = [0]
        visited = set()
        for j in range(k):
            next_now = P[now] - 1
            if next_now not in visited:
                score.append(score[-1] + C[next_now])
                visited.add(next_now)
                now = next_now
                cnt += 1
            else:
                break
        score.pop(0)
        if k - cnt == 0:
            res = max(res, max(score))
        else:
            if score[-1] <= 0:
                res = max(res, max(score))
            else:
                q, r = divmod(k, cnt)
                if r == 0:
                    res = max(res, max(score) + score[-1] * q)
                else:
                    res = max(res, max(score[:r]) + score[-1] * q, max(score[r:]) + score[-1] * (q - 1))
    print(res)


if __name__ == '__main__':
    resolve()

Submission status: Wrong Answer

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

ans = -10**10
for i in range(N):
    T = []
    Check = [0]*N
    move = i
    count = 1
    while(True):
        if Check[move] != 0:
            break
        Check[move] = count
        T.append(C[P[move]])
        move = P[move]
        count += 1
    s = Check[move] - 1
    result_1 = -10**10
    total = 0
    for j in range(min(s, K)):
        total += T[j]
        result_1 = max(result_1, total)
    result_2 = -10**10
    total = 0
    for j in range(min(len(T), K)):
        total += T[j]
        result_2 = max(result_2, total)
    result_3 = 0
    if K >= len(T):
        result_3 += sum(T[:s])
        result_3 += sum(T[s:])*((K - len(T[:s])) // len(T[s:]))
        total = result_3
        for j in range((K - len(T[:s])) % len(T[s:])):
            total += T[j]
            result_3 = max(result_3, total)
    ans = max([result_1, result_2, result_3, 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() ) )

def solve( start ):
    current = p[ start ] - 1
    l = 1
    score = c[ current ]
    while current != start:
        current = p[ current ] - 1
        l += 1
        score += c[ current ]
    if l >= k:
        current = start
        max_score = 0
        cur_score = 0
        for i in range( k ):
            current = p[ current ] - 1
            cur_score += c[ current ]
            if max_score < cur_score or i == 0:
                max_score = cur_score
        return max_score
    else:
        if score > 0:
            score = score * ( k // l )
            current = start
            max_score = 0
            cur_score = 0
            for _ in range( k % l ):
                current = p[ current ] - 1
                cur_score += c[ current ]
                if max_score < cur_score:
                    max_score = cur_score
            return max_score + score
        else:
            score = 0
            current = start
            max_score = 0
            cur_score = 0
            for i in range( k % l ):
                current = p[ current ] - 1
                cur_score += c[ current ]
                if max_score < cur_score or i == 0:
                    max_score = cur_score
            return max_score

best_score = - ( 10 ** 10 )
for i in range( n ):
    now_score = solve( i )
    if best_score < now_score:
        best_score = now_score
print( best_score )

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
# map(int, input().split())

def junkan_max_score(junkan, C, K):
    junkan_scores = [C[junkan[j+1]] if j != len(junkan)-1 else C[junkan[0]]
                    for j in range(len(junkan))
                    ]

    n_junkan = int(K/len(junkan))
    if n_junkan == 0 or sum(junkan_scores) <= 0:
        base_score = 0
    else:
        base_score = n_junkan*sum(junkan_scores)
    nokori_K = K-(n_junkan*len(junkan))
    if nokori_K == 0:
        return base_score
    else:
        return base_score+max([sum(junkan_scores[:i+1]) for i in range(nokori_K)])

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

p_junkan = {i:[i] for i in range(N)}

for i, lst in p_junkan.items():
    j = P[i]-1
    while j != i:
        lst.append(j)
        j = P[j]-1


junkan_max = [junkan_max_score(lst, C, K) for i,lst in p_junkan.items()]
print(max(junkan_max))

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)

def solve():
    N, K = map(int, input().split())
    Ps = list(map(lambda x: int(x)-1, input().split()))
    Cs = list(map(int, input().split()))

    cycless = [[] for _ in range(N)]
    useds = [0] * N
    for no in range(N):
        if useds[no]: continue
        x = no
        while True:
            useds[x] = 1
            cycless[no].append(Cs[x])
            x = Ps[x]
            if x == no:
                break

#    for no in range(N):
#        print('# no:', no, '/ cycless[no]:', cycless[no], file=sys.stderr)

    ans = -float('inf')
    for no in range(N):
        if not cycless[no]: continue
        L = len(cycless[no])
        accCycles = list(accumulate([0]+cycless[no]+cycless[no]))
        sumC = sum(cycless[no])
#        print('\n# no:', no, '/ sumC:', sumC, file=sys.stderr)
        if sumC > 0:
            num = K//L
            score = -float('inf')
            K %= L
            for M in range(K+1):
                for st in range(L):
                    s = accCycles[st+M] - accCycles[st]
                    if s > score:
                        score = s
            score += sumC * num
        else:
            score = -float('inf')
            K = K if K <= L else L
            for M in range(1, K+1):
                for st in range(L):
                    s = accCycles[st+M] - accCycles[st]
                    if s > score:
                        score = s
        if score > ans:
            ans = score
#        print('# no:', no, '/ score:', score, file=sys.stderr)

    print(ans)


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()))
for i in range(N):
  P[i]-=1
INF=-(10**20)
X=[[INF]*(N+1) for i in range(N)]
Y=[0]*N
Z=[0]*N
R=[0]*N
S=set()
V=0
for i in range(N):
  S=set()
  V=i
  S.add(i)
  for j in range(N):
    V=P[V]
    if V in S:
      Z[i]=V
      break
  X[i][0]=0
  for j in range(N):
    Y[i]+=1
    V=P[V]
    X[i][j+1]=X[i][j]+C[V]
    if Z[i]==V:
      R[i]=X[i][j+1]
      break
A=INF
Q=0
T=0
U=0
D=0
E=0
for i in range(N):
  D=K
  V=i
  E=0
  for j in range(min(N,K)):
    if Z[i]==V:
      break
    V=P[V]
    E+=C[V]
    D-=1
  D,K=K,D
  if R[i]<=0:
    for j in range(1,min(N,K)+1):
      A=max(A,X[i][j]+E)
  else:
    Q=R[i]*max((K//Y[i])-1,0)
    T=0
    U=INF
    V=i
    for j in range(min((K%Y[i])+Y[i],K)):
      V=P[V]
      T+=C[V]
      U=max(T,U)
    Q+=T
    A=max(A,Q+E)
  D,K=K,D
print(A)

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    N,K=list(map(int,sys.stdin.readline().split()))
    P=list(map(int,sys.stdin.readline().split()))
    C=list(map(int,sys.stdin.readline().split()))

    output=-10**12

    lst=[[0]*(N+1) for _ in range(N)]
    for i in range(N):
        st=set()
        now=i
        count=0
        score=0
        while True:
            count+=1
            now=P[now]-1

            if now in st:
                count-=1
                break
    
            lst[i][count]=lst[i][count-1]+C[now]
            st.add(now)
            
            if count==K:
                break
        
        if lst[i][count]>0 and K>=count:
            if K%count:
                s=lst[i][count]*(K//count)+max(lst[i][1:K%count+1])
            else:
                s=lst[i][count]*(K//count)
        else:
            s=max(lst[i][1:count+1])
        output=max(output,s)

    print(output)

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

ans = []
for u in range(N):
    v = P[u] - 1
    cnt = C[v]
    val = cnt
    jump = 1

    # Jump to limit or loop
    while u != v and jump < K:
        v = P[v] - 1
        cnt += C[v]
        val = max(val, cnt)
        jump += 1

    # Reduce residual to < K
    if jump < K:
        res = K // jump - 1
        if cnt > 0:
            cnt += cnt * res
            val = max(val, cnt)
        jump += jump * res

    # Residual steps
    v = u
    while jump < K:
        v = P[v] - 1
        cnt += C[v]
        val = max(val, cnt)
        jump += 1

    ans.append(val)

print(max(ans))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

N, K = map(int, input().split())
P = list(map(lambda x: int(x)-1, input().split()))
C = list(map(int, input().split()))
# print()
# print(*P)
# print(*C)
x = 0
used = [0] * N
path = defaultdict(list)
score = defaultdict(list)
for i in range(N):
    if used[i]:
        continue
    x = i
    while used[x] == 0:
        used[x] = 1
        path[i].append(x)
        score[i].append(C[x])
        x = P[x]
ans = -float('inf')
for r in path:
    pa, sc, le = path[r], score[r], len(path[r])
    # print(pa, sc, le)
    for i in range(le-1):
        sc[i+1] += sc[i]
    tmp = sc[-1] * (K // le)
    if tmp <= 0:
        m = -float('inf')
        for i in range(len(pa)):
            for j in range(i+1, len(pa)):
                if j - i <= K:
                    m = max(m, sc[j] - sc[i])
                if le - j + i <= K:
                    m = max(m, sc[le-1] - sc[j] + sc[i])
        ans = max(ans, m)
    else:
        k = K % le
        m = -float('inf')
        for i in range(le):
            for j in range(i+1, le):
                if j - i <= k:
                    m = max(m, sc[j] - sc[i])
                if le - j + i <= k:
                    m = max(m, sc[le-1] - sc[j] + sc[i])
        ans = max(ans, m + tmp)

        k = K % le + le
        m = -float('inf')
        for i in range(le):
            for j in range(i+1, le):
                if j - i <= k:
                    m = max(m, sc[j] - sc[i])
                if le - j + i <= k:
                    m = max(m, sc[le-1] - sc[j] + sc[i])
        ans = max(ans, m + tmp - sc[-1])
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    from sys import setrecursionlimit, stdin, stderr
    from os import environ
    from collections import defaultdict, deque, Counter
    from math import ceil, floor
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7
    INF = 10**18+10
    N,K = LMIIS()
    P = list(map(lambda x: int(x)-1,input().split()))
    C = LMIIS()
    score_sets = []
    used = [False]*N
    tmp = P[0]
    for i in range(N):
        if not used[i]:
            tmp = i
            score_set = []
            while not used[tmp]:
                used[tmp] = True
                tmp = P[tmp]
                score_set.append(C[tmp])
            score_sets.append(score_set)
        
    ans = -INF
    for score_set in score_sets:
        # 合計が最大になる区間を探す
        tmp_max = -INF
        base_cum = 0
        tmp_score_set = score_set + score_set
        sum_score_set = sum(score_set)
        if sum_score_set > 0:
            base_cum = sum_score_set * (K//len(score_set))
            K = K%len(score_set)
        for i in range(len(score_set)*2):
            cum = base_cum
            for j in range(i,min(len(score_set)*2,i+K)):
                cum += tmp_score_set[j]
                tmp_max = max(tmp_max,cum)
        ans = max(ans,tmp_max)
                
    print(ans)



    
main()

Submission status: Wrong Answer

Solution code:
def solve(n,x,k):
  ans=-10**20
  s=0
  sx=sum(x)
  for i in range(n):
    s+=x[i]
    d=((k-i-1)//n)*sx
    ans=max(ans,s+d,s)
  return ans

n,k=map(int,input().split())
p=list(map(lambda x:int(x)-1,input().split()))
c=list(map(int,input().split()))
ans=-10**20
for i in range(n):
  x=[c[i]]
  j=p[i]
  while i!=j:
    x.append(c[j])
    j=p[j]
  x=x[1:]+[x[0]]
  ans=max(ans,solve(len(x),x,k))
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()))
score = []
for i in range (1,n+1):
    num = i
    total = 0
    s =[]
    for j in range (k):
        total += c[num-1]
        num = p[num-1]
        s.append(total)
        if num == i:
            break
    if k <= len(s):
        ss = s[:k]
        score.append(max(ss))
    else:
        if s[-1] < 0:
            score.append(max(s))
        else:
            N =  k//len(s)
            if  k % len(s) == 0:
                score.append(N*s[-1])
            else:
                ss = s[:(k % len(s))]
                score.append(N*s[-1] + max(ss))

print(max(score))