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:
mi=-(10**9+1)
n,k=[int(x) for x in input().split()]
p=[int(x) for x in input().split()]
c=[int(x) for x in input().split()]

#ループの最大値を求める
mxs=mi
otl=mi
lpc={-1:1}
for i in range(n):
    chkr={i:1}
    wks=0
    nxt=i
    for _ in range(n):
        nxt=p[nxt]-1
        if chkr.get(nxt):
            wks+=c[nxt]
            otl=max(otl,wks)
            break
        chkr[nxt]=1
        wks+=c[nxt]
        otl=max(otl,wks)
    if mxs<wks:
        mxs=wks
        lpc=chkr
dv=k//len(lpc)
rst=k%len(lpc)

mxr=0
for i in lpc.keys():
    wks=0
    nxt=i
    for _ in range(rst):
        nxt=p[nxt]-1
        wks+=c[nxt]
        mxr=max(mxr,wks)

ans=max(dv*mxs+mxr,otl)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
import numba
from numba import jit
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@jit
def main(k,p,c):
  n=len(p)
  last=k%n
  by_last=k//n
  sum1=sum(c)
  cnt=sum1*by_last
  if sum1<0:
    for i in range(n):
      ans=-1000000000
      nxt=i
      for j in range(n):
          nxt=p[nxt]-1
          ans+=c[nxt]
          cnt=max(ans,cnt)
    return cnt
  else:
    for i in range(n):
      ans=sum1*by_last
      nxt=i
      for j in range(last):
        nxt=p[nxt]-1
        ans+=c[nxt]
        cnt=max(ans,cnt)
    return cnt

n,k = map(int, readline().split())
p = np.array(readline().split(), np.int64)
c = np.array(readline().split(), np.int64)
print(main(k,p,c))

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=0
res=[True for _  in range(n)]
res2=[]

for i in range(n):
    if res[i]:
        res[i]=False
        res2.append([])
        res2[-1].append(c[i])
        res3=p[i]-1
        while res3!=i:
            res[res3]=False
            res2[-1].append(c[res3])
            res3=p[res3]-1

sum=[0 for _ in range(len(res2))]
sum2=[0 for _ in range(len(res2))]
res5=False

for i in range(len(res2)):
    l=len(res2[i])
    mod=k%l
    if mod==0:
        mod=l
    for j in range(mod):
        res2[i].append(res2[i][j])
    l2=len(res2[i])
    count=0
    res4=0
    for j in range(l2):
        if j<l:
            sum[i]+=res2[i][j]
        if res2[i][j]<=0:
            sum2[i]=max([res4,sum2[i]])
            count=0
            res4=0
        else:
            res5=True
            count+=1
            if count>mod:
                res4+=res2[i][j]-res2[i][j-mod]
            else:
                res4+=res2[i][j]
            sum2[i]=max([res4,sum2[i]])

    if count>0:
        sum2[i]=max([res4,sum2[i]])
    if sum[i]>=0 and mod!=l:
        s=sum[i]*(k//l)+sum2[i]
    elif sum[i]>=0 and mod==l:
        s=sum[i]*(k//l)
    else:
        s=sum2[i]
    if s>score:
        score=s
        res5=True
    if not res5:
        score=max(res2[i])


print(score)

Submission status: Wrong Answer

Solution code:
def max2(x,y):
    return x if x > y else y

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

off = max(C)
m2 = off
for i in range(N):
    tmp = 0
    m1 = off
    l = i
    S = 0
    k = 0
    for j in range(N):
        S += C[l]
        l = P[l] - 1
        if l==i:
            k = j+1
            break
    cnt = K // k - (K % k == 0)
    cnt = max2(0, cnt -1)
    a = K-cnt*k
    l = i
    for j in range(a):
        tmp += C[l]
        m1 = max2(m1, tmp)
        l = P[l] - 1
    if S > 0:
        m1 += cnt*S
    m2 = max2(m1, m2)

print(m2)
"""
2 4
2 1
10 -7
"""

Submission status: Wrong Answer

Solution code:
import sys
import math
import collections
import bisect
import itertools

# import numpy as np

sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip().split())
na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))


# ===CODE===

# https://note.nkmk.me/python-union-find/

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


def main():
    n, k = ns()
    p = na1()
    c = na()

    uf = UnionFind(n)
    for i, pi in enumerate(p):
        uf.union(i, pi)

    cycledist = [[-INF for _ in range(2)] for __ in range(n)]
    for lis in uf.all_group_members().values():
        tmp = 0
        l = len(lis)
        for idx in lis:
            tmp += c[idx]
            cycledist[idx][1] = l
        for idx in lis:
            cycledist[idx][0] = tmp

    ans = -INF

    for i in range(n):
        t = cycledist[i][0] * (k // cycledist[i][1])
        if t >= 0:
            ans = t
        tmp_ans = max(0, t)

        tmp = 0
        idx = i
        for j in range(k % cycledist[i][1]):
            tmp += c[p[idx]]
            idx = p[idx]
            ans = max(ans, tmp_ans + tmp)

        tmp = 0
        idx = i
        for j in range(min(k, n)):
            tmp += c[p[idx]]
            idx = p[idx]
            ans = max(ans, tmp)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
mi=-(10**9+1)
n,k=[int(x) for x in input().split()]
p=[int(x) for x in input().split()]
c=[int(x) for x in input().split()]

#ループの最大値を求める
mxs=mi
otl=mi
lpc={-1:1}
for i in range(n):
    chkr={i:1}
    wks=0
    nxt=i
    for _ in range(n):
        nxt=p[nxt]-1
        if chkr.get(nxt):
            wks+=c[nxt]
            break
        chkr[nxt]=1
        wks+=c[nxt]
        otl=max(otl,wks)
    if mxs<wks:
        mxs=wks
        lpc=chkr
dv=k//len(lpc)
rst=k%len(lpc)

mxr=0
for i in lpc.keys():
    wks=0
    nxt=i
    for _ in range(rst):
        nxt=p[nxt]-1
        wks+=c[nxt]
        mxr=max(mxr,wks)

ans=max(dv*mxs+mxr,otl)
print(ans)

Submission status: Wrong Answer

Solution code:
import math
import numpy as np
import collections
import bisect
from collections import deque
from copy import copy, deepcopy


def cumsum(xs):
  result = [xs[0]]
  for x in xs[1:]:
    result.append(result[-1] + x)
  return result
 
def main():
    N,K = map(int,input().split())
    P = list(map(int,input().split()))
    C = list(map(int,input().split()))
    ans=-10e10
    tmp_sum_list = [None for i in range(N)]
    for p in range(1,N+1):
        _p=p
        end=False
        tmp_list=[]
        p_list=[]
        if tmp_sum_list[p-1] is None:
            for i in range(N):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_sum=sum(tmp_list)
            tmp_len=len(tmp_list)
            for _p in p_list:
                tmp_sum_list[_p-1]=(tmp_sum,tmp_len)

        if tmp_sum_list[p-1][0]<=0:
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            for i in range(tmp_sum_list[p-1][1]):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            continue
            #tmp_max=max(cumsum(tmp_list))
            cumsum(tmp_list)
            tmp_ans=tmp_max
        else:
            tmp_ans=(K//(tmp_sum_list[p-1][1]))*tmp_sum_list[p-1][0]
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            mod = K%tmp_sum_list[p-1][1]
            if mod!=0:
                for j in range(mod):
                    _p=P[_p-1]
                    tmp_list.append(C[_p-1])
                continue
                #tmp_max=max(cumsum(tmp_list))
                cumsum(tmp_list)
            continue
            tmp_ans+=tmp_max

        ans = max(ans,tmp_ans)
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = [int(pn) for pn in input().split()]
c = [int(cn) for cn in input().split()]
ans = -(10 ** 9)
for start in range(n):
  scores = []
  current = p[start] - 1
  score = c[current]
  scores.append(score)
  period = 1
  isCircular = False
  for _ in range(k - 1):
    current = p[current] - 1
    score += c[current]
    scores.append(score)
    period += 1
    isCircular = (current == start)
    if isCircular:
      break
  if isCircular and score:
    loops, remaining = divmod(k, period)
    max_remaining = max(0, max(scores[:remaining])) if remaining else 0
    score = max(score * loops + max_remaining, *scores)
  else:
    score = max(scores)
  if score > ans:
    ans = score

print(ans)

Submission status: Wrong Answer

Solution code:
import math
import numpy as np
import collections
import bisect
from collections import deque
from copy import copy, deepcopy


def cumsum(xs):
  result = [xs[0]]
  for x in xs[1:]:
    result.append(result[-1] + x)
  return result
 
def main():
    N,K = map(int,input().split())
    P = list(map(int,input().split()))
    C = list(map(int,input().split()))
    ans=-10e10
    tmp_sum_list = [None for i in range(N)]
    for p in range(1,N+1):
        _p=p
        end=False
        tmp_list=[]
        p_list=[]
        if tmp_sum_list[p-1] is None:
            for i in range(N):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_sum=sum(tmp_list)
            tmp_len=len(tmp_list)
            for _p in p_list:
                tmp_sum_list[_p-1]=(tmp_sum,tmp_len)

        if tmp_sum_list[p-1][0]<=0:
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            for i in range(tmp_sum_list[p-1][1]):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            #tmp_max=max(cumsum(tmp_list))
            cumsum(tmp_list)
            continue
            tmp_ans=tmp_max
        else:
            tmp_ans=(K//(tmp_sum_list[p-1][1]))*tmp_sum_list[p-1][0]
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            mod = K%tmp_sum_list[p-1][1]
            if mod!=0:
                for j in range(mod):
                    _p=P[_p-1]
                    tmp_list.append(C[_p-1])
                #tmp_max=max(cumsum(tmp_list))
                cumsum(tmp_list)
            continue
            tmp_ans+=tmp_max

        ans = max(ans,tmp_ans)
    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()))
vals = [0 for _ in range(n)]
routes = [0 for _ in range(n)]
counts = [0 for _ in range(n)]
ans = [0 for _ in range(n)]

for i in range(n):
    if vals[i] != 0:
        continue
    route = set()
    start = i
    val, val0 = 0, -float('inf')
    count = 0
    while not start in route:
        route.add(start)
        start = p[start]-1
        val += c[start]
        val0 = max(val, val0)
        count += 1
    for j in route:
        vals[i] = val0
        counts[i] = count

for i in range(n):
    val = 0
    start = i
    for j in range(k%counts[i]):
        start = p[start]-1
        val += c[start]
    ans[i] = vals[i]*(k//counts[i])+val
print(max(ans))

Submission status: Wrong Answer

Solution code:
import math
import numpy as np
import collections
import bisect
from collections import deque
from copy import copy, deepcopy


def cumsum(xs):
  result = [xs[0]]
  for x in xs[1:]:
    result.append(result[-1] + x)
  return result
 
def main():
    N,K = map(int,input().split())
    P = list(map(int,input().split()))
    C = list(map(int,input().split()))
    ans=-10e10
    tmp_sum_list = [None for i in range(N)]
    for p in range(1,N+1):
        _p=p
        end=False
        tmp_list=[]
        p_list=[]
        if tmp_sum_list[p-1] is None:
            for i in range(N):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_sum=sum(tmp_list)
            tmp_len=len(tmp_list)
            for _p in p_list:
                tmp_sum_list[_p-1]=(tmp_sum,tmp_len)

        if tmp_sum_list[p-1][0]<=0:
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            for i in range(tmp_sum_list[p-1][1]):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_max=max(cumsum(tmp_list))
            continue
            tmp_ans=tmp_max
        else:
            tmp_ans=(K//(tmp_sum_list[p-1][1]))*tmp_sum_list[p-1][0]
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            mod = K%tmp_sum_list[p-1][1]
            if mod!=0:
                for j in range(mod):
                    _p=P[_p-1]
                    tmp_list.append(C[_p-1])
                tmp_max=max(cumsum(tmp_list))
            continue
            tmp_ans+=tmp_max

        ans = max(ans,tmp_ans)
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import math
import numpy as np
import collections
import bisect
from collections import deque
from copy import copy, deepcopy
 
 
def main():
    N,K = map(int,input().split())
    P = list(map(int,input().split()))
    C = list(map(int,input().split()))
    ans=-10e10
    tmp_sum_list = [None for i in range(N)]
    for p in range(1,N+1):
        _p=p
        end=False
        tmp_list=[]
        p_list=[]
        if tmp_sum_list[p-1] is None:
            for i in range(N):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_sum=sum(tmp_list)
            tmp_len=len(tmp_list)
            for _p in p_list:
                tmp_sum_list[_p-1]=(tmp_sum,tmp_len)

        if tmp_sum_list[p-1][0]<=0:
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            for i in range(tmp_sum_list[p-1][1]):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            continue
            tmp_ans=tmp_max
        else:
            tmp_ans=(K//(tmp_sum_list[p-1][1]))*tmp_sum_list[p-1][0]
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            mod = K%tmp_sum_list[p-1][1]
            if mod!=0:
                for j in range(mod):
                    _p=P[_p-1]
                    tmp_list.append(C[_p-1])
                tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            continue
            tmp_ans+=tmp_max

        ans = max(ans,tmp_ans)
    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()))
INF = 99999999999

ind = 0
path = [[]]
cost = [[]]
path_i = 0
while True:
    path[path_i].append(ind)
    cost[path_i].append(C[ind])
    pre_ind = ind
    if P[P[pre_ind]-1] == INF:
        for i in range(len(P)):
            if P[i] != INF and i != ind:
                ind = i
                path_i += 1
                path.append(list())
                cost.append(list())
                break
    else:
        ind = P[ind]-1

    P[pre_ind] = INF

    if len(set(P)) == 1:
        break

max_c = -INF
for i in range(len(path)):
    for j in range(len(path[i])):
        if K > len(path[i]):
            if sum(cost[i]) > 0:
                tmp_c = sum(cost[i]) * (K // len(path[i]))
                tmp_c += sum(cost[i][j:j+(K % len(path[i]))])
            else:
                tmp_c = cost[i][j]
        else:
            if sum(cost[i]) > 0:
                tmp_c = sum(cost[i][j:j+(K % len(path[i]))])
            else:
                tmp_c = cost[i][j]

        if max_c < tmp_c:
            max_c = tmp_c


print(max_c)

Submission status: Wrong Answer

Solution code:
import sys
import math
import collections
import bisect
import itertools

# import numpy as np

sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip().split())
na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))


# ===CODE===

# https://note.nkmk.me/python-union-find/

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


def main():
    n, k = ns()
    p = na1()
    c = na()

    uf = UnionFind(n)
    for i, pi in enumerate(p):
        uf.union(i, pi)

    cycledist = [[-INF for _ in range(2)] for __ in range(n)]
    for lis in uf.all_group_members().values():
        tmp = 0
        l = len(lis)
        for idx in lis:
            tmp += c[idx]
            cycledist[idx][1] = l
        for idx in lis:
            cycledist[idx][0] = tmp

    ans = -INF

    for i in range(n):
        tmp_ans = max(0, cycledist[i][0] * (k // cycledist[i][1]))

        tmp = 0
        idx = i
        for j in range(k % cycledist[i][1]):
            tmp += c[p[idx]]
            idx = p[idx]
            ans = max(ans, tmp_ans + tmp)

        tmp = 0
        idx = i
        for j in range(min(k, n)):
            tmp += c[p[idx]]
            idx = p[idx]
            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()))
score=0
res=[True for _  in range(n)]
res2=[]

for i in range(n):
    if res[i]:
        res[i]=False
        res2.append([])
        res2[-1].append(c[i])
        res3=p[i]-1
        while res3!=i:
            res[res3]=False
            res2[-1].append(c[res3])
            res3=p[res3]-1

sum=[0 for _ in range(len(res2))]
sum2=[0 for _ in range(len(res2))]
res5=False

for i in range(len(res2)):
    l=len(res2[i])
    mod=k%l
    if mod==0:
        mod=l
    for j in range(mod):
        res2[i].append(res2[i][j])
    l2=len(res2[i])
    count=0
    res4=0
    for j in range(l2):
        if j<l:
            sum[i]+=res2[i][j]
        if res2[i][j]<=0:
            sum2[i]=max([res4,sum2[i]])
            count=0
            res4=0
        else:
            res5=True
            count+=1
            if count>mod:
                res4+=res2[i][j]-res2[i][j-mod]
            else:
                res4+=res2[i][j]
            sum2[i]=max([res4,sum2[i]])

    if count>0:
        sum2[i]=max([res4,sum2[i]])
    s=sum[i]*(k//l)+sum2[i] if sum[i]>0 else sum2[i]
    if s>score:
        score=s
        res5=True
    if not res5:
        score=max(res2[i])


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

visited=[]
tempv=[]
sets=[]
if sum(1 for i in C if i<=0)==N:
    print(max(C))
    exit()
i=0
while True:
    if not(i in visited):
        visited.append(i)
        tempv.append(i)
        i=P[i]-1
    elif len(visited)==N:
        sets.append(tempv)
        tempv=[]
        break
    else:
        sets.append(tempv)
        tempv=[]
        for k in range(N):
            if not(k in visited):
                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())
P = list(map(lambda x:int(x) - 1, input().split()))
C = list(map(int, input().split()))

#各地点からN回移動したときのスコアをあらかじめ求める
score = [[0 for j in range(N + 1)] for i in range(N)]
loop = [None for _ in range(N)]

for i in range(N):
    tmp = i
    flag = False
    for j in range(1, N + 1):
        tmp = P[tmp]
        score[i][j] = score[i][j - 1] + C[tmp]
        if tmp == i and not flag:
            loop[i] = j
            flag = True

if K <= N:
    res = -10**20
    for i in range(N):
        for j in range(1, K + 1):
            res = max(res, score[i][j])
    print(res)

else:
    res = -10**20
    for i in range(N):
        for j in range(1, N + 1):
            res = max(res, score[i][j])
    for i in range(N):
        if score[i][loop[i]] > 0:
            s = score[i][loop[i]] * (K // loop[i])
            for j in range(K % loop[i] + 1):
                res = max(res, s + score[i][j])
        else:
            res = max(res, score[i][loop[i]])
    print(res)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
ppp = list(map(int, input().split()))
ccc = list(map(int, input().split()))
aaa = []
S = set(range(N))
while S:
    p = list(S)[0]
    D = set()
    a = []
    for _ in range(2 * N):
        p = ppp[p] - 1
        if p in D:
            break
        D.add(p)
        a.append(ccc[p])
    a = a + a
    aaa.append(a)
    S -= D
ans = - 10 ** 13
for a in aaa:
    length = len(a) // 2
    MMM = [0] * (length + 1)
    MMM[0] = - 10 ** 13
    for i in range(1, length):
        acc = sum(a[:i])
        M = acc
        for j in range(i, len(a) - 1):
            acc -= a[j - i]
            acc += a[j]
            M = max(M, acc)
        MMM[i] = M
    MMM[length] = sum(a) // 2
    q, r = divmod(K, length)
    tem = max(MMM[-1] * q + max(MMM[:r + 1]), max(MMM))
    ans = max(ans, tem)
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()))

ans = -1000000000
for i in range(n):
    now = i
    j = 0
    # visited = deque()
    score = deque([0])
    # isLoop = True
    while j < k:
        # visited.append(now)
        score.append(score[j] +c[p[now]-1])
        now = p[now]-1
        j += 1
        if now == i:
            break
    ans = max(ans, max(list(score)[1:]))
    if j < k and score[-1] > 0:
        loop_num = k//j
        rest = k%j
        ans = max(ans, max(list(score)[:rest+2])+loop_num*score[-1] )
        ans = max(ans, max(list(score))+(loop_num-1)*score[-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()))

ans = -10000000

if K <= 50000:
    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
        if amari == 0:
            amari = counter
            shou -= 1
            new_ans = max(new_ans, value*shou, value*(shou+1)  )
        else:
            new_ans = max(new_ans, value*shou)
        tmp_ans = value*shou    
        
        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(loop[0][0], ans, new_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 = c[0]
jud = []
for i in range(n):
    if i not in jud:
        l = []
        j = p[i] - 1
        while j not in jud:
            jud.append(j)
            l.append(c[p[j]-1])
            j = p[j] - 1
        le = len(l)
        # l *= (k//le +2)
        # for ii in range(le):
        #     val = l[ii]
        #     ans = max(ans,val)
        #     for cnt in range(ii+1, ii + k):
        #         val += l[cnt]
        #         ans = max(val, ans)

print(ans)

Submission status: Wrong Answer

Solution code:
#!python3

import sys
iim = lambda: map(int, sys.stdin.readline().rstrip().split())

from heapq import heappush, heappop, heapify


def resolve():
    N, K = iim()
    P = list(i-1 for i in iim())
    C = list(iim())

    inf = float("inf")
    vis = [0] * N
    dp = [0]* N
    aa = []
    for n in range(N):
        if vis[n]:
            continue
        pos = n
        dp = []
        while True:
            if vis[pos]:
                break
            vis[pos] = True
            pos = P[pos]
            dp.append(C[pos])
        aa.append(dp)

    def calc(a, k):
        n = len(a)
        if n < k:
            sm = sum(a)
            if sm > 0:
                i, n = divmod(k, n)
                sm *= i

                if n == 0:
                    return sm
            else:
                sm = 0
        else:
            sm = 0

        if n == 1:
            return max(a) + sm

        dp = [0] * n
        ans = -inf
        for i in range(-n+1, n):
            ai = a[i]
            for j in range(n):
                dp[j] += ai
            for j in range(min(i+n-1, n)):
                dp[j] -= a[i-j-1]

            ans = max(ans, *dp)

        return ans + sm

    ans = -inf
    for a in aa:
        ans = max(ans, calc(a, K))
    print(ans)





if __name__ == "__main__":
    resolve()