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 bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    N, K = LI()
    P = LI_()
    C = LI()

    ans = -INF
    for i in range(N):
        visited = [False] * N
        c = i
        loop = [c]
        while True:
            visited[c] = True
            c = P[c]
            if visited[c]:
                break
            loop.append(c)
        # print(loop)
        len_loop = len(loop)
        l  = [C[i] for i in loop]
        score_loop = sum(l)

        tmp = 0
        # ループさせる場合のその分の加算
        if K > len_loop and score_loop > 0:
            tmp += K // len_loop * score_loop

        # ループではない部分
        K_no_loop =  K if K == len_loop else K % len_loop
        # print(l)
        l_cum = [0] * (len_loop + 1)
        for j in range(len_loop):
            l_cum[j+1] = l[j] + l_cum[j]
        # print(l_cum)

        max_cand = -INF
        for j in range(K_no_loop):
            for k in range(len_loop - j):
                # print(j+k+1, k)
                max_cand = max(l_cum[j+k+1] - l_cum[k], max_cand)
        tmp += max_cand

        ans = max(tmp, ans)

    print(ans)

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()))
loop_flags = [False] * N
loops = []
for i in range(N):
    if loop_flags[i]:
        continue
    next_cell = i
    loop = []
    while not loop_flags[next_cell]:
        loop_flags[next_cell] = True
        loop.append(C[next_cell])
        next_cell = P[next_cell] - 1
    if loop:
        loops.append(loop)
# print(loops)

ans = -float('inf')
for loop in loops:
    sum_score = sum(loop)
    if sum_score > 0:
        sum_val = sum_score * (K // len(loop))
        remain_K = K % len(loop)
    else:
        sum_val = 0
        remain_K = min(len(loop), K)
    for i in range(1, len(loop) + 1):
        if i > remain_K:
            break
        target = sum_val
        target += sum(loop[:i])
        ans = max(target, ans)
        for j in range(len(loop)):
            target = target - loop[j] + loop[(i + j) % len(loop)]
            ans = max(target, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
n,k = list(map(int,input().split()))
p = list(map(int,input().split()))
c = list(map(int,input().split()))
was = [False]*n
sums = []
for i in range(n):
    if not was[i]:
        iWas = [False]*n
        pos = i
        sumn = [c[i]]
        while not iWas[pos]:
            iWas[pos] = True
            was[pos] = True
            pos = p[pos]-1
            sumn+=[c[pos]]
        sumn = sumn[:-1]
        sums.append(sumn)
m = -9999999999999999999999999
for i in range(len(sums)):
    totS = sum(sums[i])
    l = len(sums[i])
    for g in range(len(sums[i])):
        arr = []
        s = 0
        for j in range(l):
            s+=sums[i][(g+j)%l]
            arr.append(s)

        if totS > 1:
            add = max(arr[:k%l]+[-99999999999999999999])
            if add != -99999999999999999999:
                m = max(m,totS*(k//l)+max(arr[:k%l]))
            else:
                m = max(m,totS*(k//l))

        else:

            m = max(m, max(arr[:min(l,k)]))
print(m)

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**20
for start in range(N):
    now = P[start]
    tmp = C[now]
    ans = max(ans, tmp)
    c = K-1
    k = 1
    kick = [tmp]
    step = None
    kick_tmp = None
    while c > 0 and k < N:
        now = P[now]
        tmp += C[now]
        ans = max(ans, tmp)
        c -= 1
        k += 1
        kick.append(tmp)
        if now == start:
            step = k
            kick_tmp = tmp
            break
    if step != None and K%step != 0:
        ans = max(ans, kick_tmp*(K//step)+max(kick[:K%step]))
print(ans)

Submission status: Wrong Answer

Solution code:
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10**9+7

Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()


n,k = Ri()
a = Ri(); a = [i-1 for i in a]
c = Ri()

lis = []
vis = [False]*n
for i in range(n):
    if not vis[i]:
        temp = []
        nex = i
        while True:
            temp.append(c[nex])
            vis[nex] = True
            nex = a[nex]
            if vis[nex] : break
        lis.append(temp)
summ = []
# print(lis)

for i in range(len(lis)):
    temp = [0]*(len(lis[i]) + 1)
    for j in range(len(lis[i])):
        temp[j+1] = temp[j] + lis[i][j]
    summ.append(temp[:])

# print(summ)
maxxans= -INF
for i in range(len(lis)):
    actualcircle = k//len(lis[i])
    # print(actualcircle)
    # maxxans = max(maxxans, actualcircle*summ[i][-1])
    for krem in range(1, min(n-1, k)+1):
        cnt = len(lis[i])
        rem = krem%cnt
        for j in range(len(lis[i])):
            tot = summ[i][-1]
            tempans = tot*(krem//cnt)
            if j + rem -1 >= cnt:
                temp = summ[i][-1] - summ[i][j]
                totrem = rem - ((cnt-1) - j +1)
                temp += summ[i][totrem]
                maxxans = max(maxxans, temp + tempans)
            else:
                maxxans = max(maxxans, tempans + summ[i][j+rem] - summ[i][j])

    for krem in range(0, k%len(lis[i])+1):
        cnt = len(lis[i])
        rem = krem%cnt
        for j in range(len(lis[i])):
            tot = summ[i][-1]
            tempans = tot*actualcircle
            if j + rem -1 >= cnt:
                temp = summ[i][-1] - summ[i][j]
                totrem = rem - ((cnt-1) - j +1)
                temp += summ[i][totrem]
                maxxans = max(maxxans, temp + tempans)
            else:
                maxxans = max(maxxans, tempans + summ[i][j+rem] - summ[i][j])
        # print(maxxans)
print(maxxans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate

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

P = [p-1 for p in P]

check = [False] * n
loops = []

for i in range(n):
    if check[i]:
        continue
    check[i] = True
    next = P[i]
    tmp = [i]
    while next != i:
        check[next] = True
        tmp.append(next)
        next = P[next]
    loops.append(tmp)


ans = 0

for loop in loops:

    num = len(loop)
    div = k // num
    r = k % num
    if r == 0:
        r = num
        div -= 1
    L = [C[p] for p in loop]

    ans_tmp = 0
    by_loop = max(sum(L), 0) * div

    L += L[:r]
    ACC = [0] + list(accumulate(L))

    for i in range(num):
            for j in range(i+1, i+r+1):
                ans_tmp = max(ans_tmp, ACC[j] - ACC[i] + by_loop)

    ans = max(ans, ans_tmp)

if ans == 0:
    print(max(C))
    exit()

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

Submission status: Wrong Answer

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

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

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

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

def score(x):#xからスタートしたスコア
    l = uf.get_size(x)
    p,r = divmod(k,l)
    tmp = [-10**15 for i in range(l+1)]#一回の累積和
    tmp_p = [0 for i in range(l+1)] #あまりを考慮したときの累積和
    if p==0:
        xt=x
        ret = 0
        mx = -10*15
        for i in range(r):
            nex = P[xt]
            ret+=C[nex]
            xt = nex
            mx = max(mx,ret)
        return mx

    gain_cycle = 0
    xt=x
    ret = 0
    for i in range(l):
        nex = P[xt]
        gain_cycle +=C[nex]
        ret+=C[nex]
        tmp[i+1] = ret
        if i<=r-1:#あまりの範囲なら
            tmp_p[i+1]=ret
        xt = nex
    if gain_cycle>=0:
        return max(tmp_p) + p* gain_cycle
    else:
        return max(tmp)

        #print(ret,"ret")

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

Submission status: Wrong Answer

Solution code:
def mss(l,length,k):
    x = - 1000000001
    for i in range(length):
        temp = 0
        for j in range(i,i+k):
            temp += l[j]
            if temp > x:
                x = temp
    return x

if __name__ == '__main__':
    N,K = map(int,input().split())
    P = [int(p)-1 for p in input().split()]
    C = [int(c) for c in input().split()]
    #閉路の探索
    L_close = []
    Done = [0] * N
    for i in range(N):
        if Done[i] == 1:
            continue
        score = []
        #start
        Done[i] = 1
        #Next
        p = P[i]
        Done[p] = 1
        score.append(C[p])
        while p != i:
            p = P[p]
            Done[p] = 1
            score.append(C[p])
        L_close.append(score)
    #それぞれの閉路に対して
    ans = - 1000000001
    for l in L_close:
        total = sum(l)
        length = len(l)
        l = l + l
        if total <= 0:
            ans = max(ans,mss(l,length,min(K,length)))
        else:
            ans = max(ans,total * (K//length) + mss(l,length,K%length))
    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()))

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

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

Submission status: Wrong Answer

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


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 main():
    n, k = MI()
    p = LI()
    c = LI()

    hairetu = [[0] for i in range(n)]
    for i in range(n):
        next_idx = i + 1
        for times in range(1, n + 1):
            next_idx = p[next_idx - 1]
            hairetu[i].append(hairetu[i][times - 1] + c[next_idx - 1])
            if next_idx == i + 1:
                break

    lengths = [0] * n
    one_roop = list(map(lambda x: x[-1], hairetu))

    for i in range(n):
        lengths[i] = len(hairetu[i]) - 1

    maxs = list(map(lambda x: max(x, 0), one_roop))
    anss = [-1 * 10 ** 9]*n
    for i in range(n):
        length = lengths[i]
        amari = k % length
        shou = k // length
        if shou == 0:
            maxs[i] = 0
        else:

            maxs[i] = shou * maxs[i]

        for j in range(1, max(2, amari + 1)):
            anss[i] = max(maxs[i] + hairetu[i][j], anss[i])

    print(max(*anss))


main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
plst = list(map(int, input().split()))
clst = list(map(int, input().split()))
check = [False for _ in range(n)]
loop_s = []
for i in range(n):
    if check[i]:
        continue
    check[i] = True
    loop = []
    start = i
    while 1:
        loop.append(clst[i])
        i = plst[i] - 1
        check[i] = True
        if i == start:
            break
    loop_s.append(loop)

ans = -10 ** 20
for loop in loop_s:
    ans_tmp = 0
    l = len(loop)
    if l <= k:
        ans_tmp = max(0, sum(loop) * (k // l - 1))
        k = k % l + l
    tmp2 = -10 ** 20
    for i in range(l):
        tmp3 = 0
        for j in range(k):
            pos = (i + j) % l
            tmp3 += loop[pos]
            tmp2 = max(tmp2, tmp3)
    ans = max(ans_tmp + tmp2, ans)
print(ans)

Submission status: Wrong Answer

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

L = [[] for i in range(n+1)]
length = [0]*(n+1)

for i in range(1,n+1):
    x = i

    s = set([])
    sw = 0
    for j in range(1,n+1):

        x = P[x]
        if P[x] in s and sw == 0:
            length[i] = j-1
            sw = 1
            
        s.add(P[x])
        point = C[x]
        if L[i] != []:
            L[i].append(L[i][-1]+C[x])
        else:
            L[i].append(C[x])
            
    if sw == 0:
        length[i] = n


ans = - float("Inf")


for i in range(1,n+1):
    m = k//length[i]
    p = k%length[i]
    
    
    
    if k > length[i]:
        
    
        if p == 0:
            point = m * L[i][length[i]-1]
        else:
            point = m * L[i][length[i]-1] + max(L[i][:p])
            
        ans = max(ans, point)
            
        ans = max(max(L[i][:]), ans)
    
    else:
        ans = max(max(L[i][:k]), ans)
        

        
print(ans)

Submission status: Wrong Answer

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

loop_list = [] # ([indexes])
loop_score_list = []
loop_index_list = [0]*N
is_included_loop = [0] * N
num_loop = 0

for start in range(N):
    if is_included_loop[start]:
        continue
    now = start
    count = 1
    visited = [-1]*N # count
    visited[now] = 0
    while True:
        now = P[now]
        if visited[now] != -1:
            terminate_count = count
            start_count = visited[now]
            loop_start_idx = now
            break
        visited[now] = count
        count += 1
    
    num_loop += 1
    now = loop_start_idx
    loop_indexes = [now]
    visited = [-1]*N
    visited[now] = 0
    count = 1
    loop_score = 0
    while True:
        now = P[now]
        if visited[now] != -1:
            break
        loop_indexes.append(now)
        visited[now] = count
        loop_index_list[now] = num_loop
        loop_score += C[now]
        is_included_loop[now] = 1
    loop_list.append(loop_indexes)
    loop_score_list.append(loop_score)


scores = []
for start in range(N):
    tmp_score = 0
    rest = K
    now = start
    while not is_included_loop[now] and rest > 0:
        now = P[now]
        rest -= 1
        tmp_score += C[now]
        scores.append(tmp_score)
    
    if rest <= 0:
        scores.append(tmp_score)
        continue
    # loop
    number_of_loop = loop_index_list[now] - 1
    one_cicle_score = loop_score_list[number_of_loop]
    if rest < len(loop_list[number_of_loop]):
        while rest >= 0:
            now = P[now]
            rest -= 1
            tmp_score += C[now]
            scores.append(tmp_score)
        continue
    else:
        n_l = rest // len(loop_list[number_of_loop])
        tmp_score += n_l * one_cicle_score
        rest -= n_l * len(loop_list[number_of_loop])
        while rest >= 0:
            now = P[now]
            rest -= 1
            tmp_score += C[now]
            scores.append(tmp_score)
        scores.append(tmp_score)
print(max(scores))

Submission status: Wrong Answer

Solution code:
import sys, math
from functools import lru_cache
from collections import defaultdict
sys.setrecursionlimit(500000)
MOD = 10**9+7

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]

def main():
    N, K = mi()
    P = list(mi())
    C = list(mi())
    m = -10**100

    loop = [(-1, 0)]*N
    for i in range(N):
        if loop[i][0] != -1:
            continue
        now = P[i]-1
        T = 1
        s = C[now]
        l = [now]
        while now != i:
            now = P[now]-1
            s += C[now]
            T += 1
            l.append(now)

        for v in l:
            loop[v] = (T, s)

    ans = -10**100
    # iから始める
    for i in range(N):
        # loopの周期、総和を取得
        T, s = loop[i]

        # loop周回回数
        n = K//T if s > 0 else 0

        # loopをn-1周した後のscore
        tmp = s*(n-1) if s > 0 else 0

        # 残り回数
        rest = K-(n-1)*T if s > 0 else T

        # 残りで移動させた時の最大値を計算
        now = i
        s = 0
        for _ in range(rest):
            now = P[now]-1
            s += C[now]
            m = max(m, s)

            ans = max(ans, tmp+m, )

    print(ans)



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**9)
N, K = map(int, input().split())
P = list(map(lambda x:int(x)-1, input().split()))
C = list(map(int, input().split()))
weight = []
visited = [0]*N
ans = - float('inf')

def dfs(u, cnt, w):
  w += [C[u]]
  visited[u] = 1
  v = P[u]
  if visited[v] != 1:
    dfs(v, cnt+1, w)
  else:
    return

for i in range(N):
  weight = []
  visited = [0]*N
  dfs(i, 1, weight)

  if len(weight) > K:
    weight = weight[:K]
    tmp = 0
    for j in range(K-1):
      weight[j+1] += weight[j]
    tmp = max(weight)
    ans = max(ans, tmp)
  else:
    s = sum(weight)
    if s > 0:
      tmp = (K//len(weight))*s
      weight = weight[:K%len(weight)]
      if len(weight) > 0:
        for j in range(len(weight)-1):
          weight[j+1] += weight[j]
        tmp += max(weight)
      ans = max(ans, tmp)
    else:
      tmp = 0
      for j in range(len(weight)-1):
        weight[j+1] += weight[j]
      tmp = max(weight)
      ans = max(ans, tmp)
print(ans)

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

Solution code:
N, K = [int(i) for i in input().split()]
P = [int(i)-1 for i in input().split()]
C = [int(i) for i in input().split()]
def f(s):
    slow = s
    fast = s
    counter = 0
    for _ in range(N):
        slow = P[slow]
        fast = P[P[fast]]
        counter += 1
        if slow == fast:
            break
    # counter = m = lambda + k * myu
    # m = lambda(開始地点) +(m - lambda)
    # lambda進むとmyuの定数倍のmがlambdaから進んだ事になるのでそこがスタート地点
    # get lambda
    slow2 = slow
    slow_start = s
    counter = 0
    for _ in range(K):
        slow2 = P[slow2]
        slow_start = P[slow_start]
        counter += 1
        if slow2 == slow_start:
            break
    lam = counter
    slow3 = slow
    counter = 0
    for _ in range(K):
        slow3 = P[slow3]
        counter += 1
        if slow3 == slow:
            break
    myu = counter
    return (lam, myu)

maxsum = -10 ** 10
for s in range(N):
    lam, myu = f(s)
    tmpmaxs = -10 ** 10
    tmp = s
    tmpsum = 0
    for _ in range(K%myu):
        tmpsum += C[tmp]
        if tmpsum > tmpmaxs:
            tmpmaxs = tmpsum
        if tmpsum < 0:
            tmpsum = 0
        tmp = P[tmp]
    # tmpmaxsは循環しない時の最大値
    tmp = s
    cirsum = 0
    cirmaxs = -10 ** 10
    cirtmps = 0

    for _ in range(myu):
        cirsum += C[tmp]
        cirtmps += C[tmp]
        if cirmaxs < cirtmps:
            cirmaxs = cirtmps
        if cirtmps < 0:
            cirtmps = 0
        tmp = P[tmp]
    tot = 0
    if cirsum <= 0:
        tot = cirmaxs
    else:
        tot = tmpsum + (cirsum) * (K//myu)
    if maxsum < tot:
        maxsum = tot

print(maxsum)

Submission status: Wrong Answer

Solution code:
#ceilevenoddformula
import math
from queue import PriorityQueue
import bisect
import copy
import time
from collections import Counter
#map(int,input().split())
#int(x) for x in input().split()
def su(x,k):
	ans=[]
	for i in range(min(k,len(x))):
		d=sum(x[:i+1])
		m=d
		for j in range(i+1,len(x)):
			d=d-x[j-i-1]+x[j]
			if m<d:
				m=d
		ans.append(m)
	return ans




n,k=map(int,input().split())
p=[int(x) for x in input().split()]
c=[int(x) for x in input().split()]
l=[]
v=set()
for i in range(n):
	if i not in v:
		f=[]
		f.append(c[i])
		v.add(i)
		x=p[i]
		while x-1 not in v:
			f.append(c[x-1])
			v.add(x-1)
			x=p[x-1]
		l.append(f)
value=float('-INF')
for i in range(len(l)):
	ans=su(l[i],k)
	if len(ans)>0:
		jk=0
		if k<len(l[i]) or sum(l[i])<=0:
			jk+=max(ans)
		elif k==len(l[i]):
			jk+=max(max(ans),sum(l[i]))
		else:
			if sum(l[i])>0:
				jk+=(k//len(l[i]))*sum(l[i])
				b=k%len(l[i])
				if b>0:
					jk+=max(ans[:b])

			value=max(value,max(ans[:min(k,len(ans))]))
		value=max(value,jk)

print(value)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate

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

P = [p-1 for p in P]

check = [False] * n
loops = []

for i in range(n):
    if check[i]:
        continue
    check[i] = True
    next = P[i]
    tmp = [i]
    while next != i:
        check[next] = True
        tmp.append(next)
        next = P[next]
    loops.append(tmp)


ans = 0

for loop in loops:

    num = len(loop)
    div = k // num
    r = k % num
    if r == 0:
        r = num
        div -= 1
    L = [C[p] for p in loop]

    ans_tmp = 0

    ryaku = 0
    if sum(L) > 0:
        ryaku = sum(L) * div

    L += L[:r]
    ACC = [0] + list(accumulate(L))

    for i in range(num):
            for j in range(i+1, i+r+1):
                ans_tmp = max(ans_tmp, ACC[j]-ACC[i]+ ryaku)

    ans = max(ans, ans_tmp)

if ans == 0:
    print(max(C))
    exit()
print(ans)