Problem:


Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



Sample input:
5 2
2 4 5 1 3
3 4 -10 -8 8


Sample output:
8

Submission status: Wrong Answer

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

score = []
for start in range(N):
  position = start
  score_tmp = []
  for k in range(K):
    position = P[position] - 1
    score_tmp.append(C[position])
    score.append(sum(score_tmp))
    if position == start:
      score_per_round = sum(score_tmp)
      length_per_round = len(score_tmp)
      nrounds = K // length_per_round
      mod = k % length_per_round

      if score_per_round > 0:
        for i_mod in range(mod):
          score.append(nrounds * score_per_round + sum(score_tmp[:i_mod]))
      #else:
      #  for i_round in range(nrounds):
      #    score.append(sum(score_tmp[:i_round + 1]))
      
      break

print(max(score))

Submission status: Wrong Answer

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

ans = -float('inf')

for i in range(n): #start
    start = i
    now = start
    total = 0
    ls = [0]

    for j in range(1, k+1):
        now = pn[now]-1
        total += cn[now]
        ans = max(ans, total)
        ls.append(total)
        if now == start:
            rp = j
            break
    else:
        continue

    if total <= 0:
        continue
    else:
        if k % rp == 0:
            ans = max(ans, total * (k//rp) - cn[start])
        else:
            s = k % rp
            ans2 = total * (k//rp) + max(ls[:s+1])- cn[start]
            ans = max(ans, ans2)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
from collections import deque, defaultdict
def main():
    n, ko = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    scores_all = deque()
    for k1 in range(n):
        scores = deque()
        kita = defaultdict(int)
        kita[k1] = ko + 1
        cnt = ko
        koko = p[k1] - 1
        scores.append(c[koko])
        kita[koko] = cnt
        cycle_long = n
        while cnt:
            cnt -= 1
            koko = p[koko] - 1
            scores.append(c[koko])
            if kita[koko]:
                cycle_long = kita[koko] - cnt
                break
            else:
                kita[koko] = cnt
        scores_a = tuple(accumulate(scores))
        if cnt:
            if scores_a[-1] > 0:
                kaisuu = ko // cycle_long
                s = scores_a[-1] * kaisuu
                amari = ko % cycle_long
                if amari:
                    s += max(scores_a[:amari])
                scores_all.append(s)
            else:
                scores_all.append(max(scores_a))
        else:
            scores_all.append(max(scores_a))
    print(max(scores_all))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    INIT = -10**9 - 1  # Cから最低一つ選択する必要がある、Cの下限よりも小さい値を暫定値とする

    N, K = map(int, input().split())
    *P, = (int(x) - 1 for x in input().split())
    *C, = map(int, input().split())

    def accumulate(a):
        s = 0
        yield s
        for x in a:
            s += x
            yield s

    ans = INIT

    grp = [-1] * N
    for gid in range(N):
        if ~grp[gid]:
            continue
        cycl = []
        curr = gid
        while grp[curr] == -1:
            cycl.append(C[curr])
            grp[curr] = gid
            curr = P[curr]

        score = 0

        L = len(cycl)
        S = sum(cycl)
        if S > 0:
            score += ((K - 1) // L) * S
        K = (K - 1) % L + 1

        *acc, = accumulate(cycl)

        partial = INIT
        for left in range(L):
            for right in range(left + 1, min(left + K, L) + 1):
                partial = max(partial, acc[right] - acc[left])
        for l_right in range(K + 1):
            for r_left in range(L, L - (K - l_right) - 1, -1):
                if l_right == 0 and r_left == L:
                    continue
                partial = max(partial, acc[l_right] + acc[L] - acc[r_left])

        ans = max(ans, score + partial)

        # print(f'{gid=}')
        # print(f'{grp=}')
        # print(f'{cycl=}')
        # print(f'{L=}')
        # print(f'{S=}')
        # print(f'{K=}')
        # print(f'{acc=}')
        # print(f'{score=}')
        # print(f'{partial=}')

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

ans = -float('inf')

for i in range(n): #start
    start = i
    now = start
    total = 0
    ls = [0]

    for j in range(1, k+1):
        now = pn[now]-1
        total += cn[now]
        ans = max(ans, total)
        ls.append(total)
        if now == start:
            rp = j
            break
    else:
        continue

    if total <= 0:
        continue
    else:
        if k % rp == 0:
            ans = max(ans, total * (k//rp) - cn[start])
        else:
            s = k % rp
            ans2 = total * (k//rp) + max(ls[:s+1])
            ans = max(ans, ans2)
print(ans)

Submission status: Wrong Answer

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

ans=max(c)
if ans<0:
    print(ans)
    exit()

for i in range(n):
    nxt=i
    lp=[]
    while 1:
        nxt=p[nxt]
        lp.append(nxt)
        if nxt==i:
            break
    rst=k%len(lp)
    nxt=i
    wks=0
    lpm=0
    for _ in range(rst):
        nxt=p[nxt]
        wks+=c[nxt]
        lpm=max(lpm,wks)

    lpc=sum(c[x] for x in lp)
    ans=max(ans,(k//len(lp))*lpc+lpm)
print(ans)

Submission status: Wrong Answer

Solution code:
def li():
    return [int(x) for x in input().split()]

N, K = li()
P = [0] + li()
C = [0] + li()

def get_cycle(start_i):
    cycle = []
    i = start_i
    while True:
        i = P[i]
        if i == start_i:
            break
        cycle.append(i)
    cycle.append(start_i)
    return cycle

def get_cycle_scores(cycle):
    score = 0
    scores = [score]
    for i in cycle:
        score += C[i]
        scores.append(score)
    return scores

max_scores = []
for start_i in range(1,N+1):
    cycle = get_cycle(start_i)
    scores = get_cycle_scores(cycle)
    # 1cycle以下の場合は全て調べればよし
    if K <= len(cycle):
        max_score = max(scores[move] for move in range(1, K+1))
        max_scores.append(max_score)
        continue
    # 1サイクルの長さ
    cycle_len = len(cycle)
    # 1サイクルごとのスコア
    score_per_cycle = scores[cycle_len]
    # ラスト1サイクルのスコア
    scores_last_cycle = []
    # 最後の1cycleの値を調べる
    for move in range(K-cycle_len+1, K+1):
        # 何周したか
        loop_cnt = move // cycle_len
        # あまり
        rest_move = move % cycle_len
        # スコア = 1周ごとのスコア * 何周したか + あまり
        score = loop_cnt * score_per_cycle + scores[rest_move]
        scores_last_cycle.append(score)

    max_scores.append(max(scores_last_cycle))

print(max(max_scores))

Submission status: Wrong Answer

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


def main():
    [n, num] = [int(e) for e in si().split()]
    pl = [int(e) for e in si().split()]
    cl = [int(e) for e in si().split()]

    M = -1000000000*5000-1

    for i in range(n):
        vis = [0 for _ in range(n)]
        val = [0 for _ in range(n)]
        flag, ith, k, idx, m, cv, cn = False, 0, num, i, 0, 0, 0
        while k > -1:
            idx = pl[idx]-1
            ith += 1
            if not flag and vis[idx]:
                flag = True
                cv = m-(val[idx]-cl[idx])
                cn = ith-vis[idx]
                rest = k//cn
                if rest:
                    m += cv*rest
                    k -= cn*rest
            elif not flag:
                vis[idx] = ith
                val[idx] = m+cl[idx]
            m += cl[idx]
            M = max(M, m)
            k -= 1
    print(M)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:

import collections

n, k = map(int, input().split())

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


def maxv(arr, k):

    n = len(arr)
    sumA = arr[:] + [0]

    for i in range(n):
        sumA[i] += sumA[i - 1]

    deque = collections.deque()

    ans = -float('inf')
    maxL = 0

    for i in range(-1, n):

        while deque and i - deque[0] > k:
            deque.popleft()

        if deque:

            temp_sum = sumA[i] - sumA[deque[0]]
            tempL = i - deque[0]

            if temp_sum > ans:
                ans = temp_sum
                maxL = tempL

            # ans = max(ans, sumA[i] - sumA[deque[0]])

        while deque and sumA[ deque[-1] ] > sumA[i]:
            deque.pop()

        deque.append(i)

    return (ans, maxL)



def sol(n, k, p, c):

    vs = set()

    p = [0] + p
    c = [0] + c

    ans = -float('inf')

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

        if i not in vs:
            
            u = i
            vs.add(u)
            temp = [ c[p[u]] ]
            
            while p[u] not in vs:

                u = p[u]
                vs.add(u)
                temp.append( c[p[u]] )

            sum_temp = sum(temp)
            n_temp = len(temp)


            max_value, max_len = maxv(temp + temp, n_temp)

            if max_len < k:

                temp_v = max_value + ((k - max_len) // n_temp) * max(sum_temp, 0)

            else:

                temp_v, xxx = maxv(temp + temp, k)

            ans = max(ans, temp_v)

            # print (ans, 'x')


            # if sum_temp <= 0:

            #     total = maxv(temp + temp, min(n_temp, k))

            #     ans = max(ans, total)

            #     continue


            # temp_k = k % n_temp

            # if temp_k == 0:
            #     temp_k = n_temp
            #     k -= n_temp

            # num_k = k // n_temp

            # total1 = maxv( temp + temp, temp_k ) + sum_temp * (num_k)

            # ans = max(ans, total1)

            # if num_k >= 1:
            #     temp_k += n_temp
            #     num_k -= 1

            #     total2 = maxv( temp + temp, temp_k ) + sum_temp * (num_k)

            #     ans = max(ans, total2)

            

            


            # print (temp, ans, '|', temp + temp, temp_k, maxv( temp + temp, temp_k ))

    if ans < 0:
        ans = max(c[1:])

    return ans


ans = sol(n, k, p, c)    

print (ans)

Submission status: Wrong Answer

Solution code:
def main():
    INIT = -10**9 - 1  # Cから最低一つ選択する必要がある、Cの下限よりも小さい値を暫定値とする

    N, K = map(int, input().split())
    *P, = (int(x) - 1 for x in input().split())
    *C, = map(int, input().split())

    def accumulate(a):
        s = 0
        yield s
        for x in a:
            s += x
            yield s

    ans = INIT

    grp = [-1] * N
    for gid in range(N):
        if ~grp[gid]:
            continue
        cycl = []
        curr = gid
        while grp[curr] == -1:
            cycl.append(C[curr])
            grp[curr] = gid
            curr = P[curr]

        score = 0

        L = len(cycl)
        S = sum(cycl)
        if S > 0:
            score += (K // L) * S
        K = (K - 1) % L + 1

        *acc, = accumulate(cycl)

        partial = INIT
        for left in range(L):
            for right in range(left + 1, min(left + K, L) + 1):
                partial = max(partial, acc[right] - acc[left])
        for l_right in range(K + 1):
            for r_left in range(L, L - (K - l_right) - 1, -1):
                if l_right == 0 and r_left == L:
                    continue
                partial = max(partial, acc[l_right] + acc[L] - acc[r_left])

        ans = max(ans, score + partial)

        # print(f'{gid=}')
        # print(f'{grp=}')
        # print(f'{cycl=}')
        # print(f'{L=}')
        # print(f'{S=}')
        # print(f'{K=}')
        # print(f'{acc=}')
        # print(f'{score=}')
        # print(f'{partial=}')

    print(ans)


if __name__ == '__main__':
    main()

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()))
mi_inf=-1e+18
seen=[False]*n
max_sum=mi_inf
log=0 
max_loop=[]
loop=[]
cnt=0
i=0
while cnt<=n:
  #print(seen)
  if seen[i]==True:
    #print('kusa')
    if max_sum<log and log!=0:
      max_loop=loop
      max_sum=log
    log=0
    loop=[]
    i=0
    while seen[i] and cnt<=n-1:i+=1
  seen[i]=True
  
  loop.append(c[i])
  log=max(log,log+c[i])
  
  i=p[i]
  cnt+=1

#print(seen)
max_loop=sorted(max_loop,reverse=True)
#print('max_sum : %s'%max_sum)
if max_sum==mi_inf:
  #print('kusa')
  max_sum=max(c)
  print(max_sum)
  exit()

if k<=len(max_loop):
  print(max(max_sum,sum(max_loop[:k])))
else:
  a,b=k//len(max_loop),k%len(max_loop)
  #print('a : %s, b : %s'%(a,b))
  print(sum(max_loop)*a+sum(max_loop[:b]))

Submission status: Wrong Answer

Solution code:
p = []
c = []

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

i = 0
while(i<n):
    d = [0]*n
    visited = [0]*n
    cnt = 0
    j=i
    answ=0
    last=i
    while(cnt<k and visited[j]==False):
        cnt+=1
        visited[j] = cnt
        d[j] = answ
        last = j
        j = p[j]
        answ+=c[j]
        best[i] = max(best[i],answ)
    
    k1 = max(k-cnt,0)
    cycle = visited[last]-visited[j]+1
    answ += (answ-d[j])*(k1//cycle)
    best[i] = max(best[i],answ)
    k1 = k1%cycle
    while(k1>0):
        j = p[j]
        answ+=c[j]
        best[i] = max(best[i],answ)
        k1-=1
    i+=1

x = max(best)
while(x<0):
    pass

print(max(best))

Submission status: Wrong Answer

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

ans = -float('inf')

for i in range(n): #start
    start = i
    now = start
    total = 0
    ls = [0]

    for j in range(1, k+1):
        now = pn[now]-1
        total += cn[now]
        ans = max(ans, total)
        ls.append(total)
        if now == start:
            rp = j
            break
    else:
        continue

    if total <= 0:
        continue
    else:
        s = k % rp
        ans2 = total * (k//rp) + max(ls[:s+1])
        ans = max(ans, ans2)
print(ans)

Submission status: Wrong Answer

Solution code:
p = []
c = []

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

i = 0
while(i<n):
    d = [0]*n
    visited = [0]*n
    cnt = 0
    j=i
    answ=0
    last=i
    while(cnt<k and visited[j]==False):
        cnt+=1
        visited[j] = cnt
        d[j] = answ
        last = j
        j = p[j]
        answ+=c[j]
        best[i] = max(best[i],answ)
    
    k1 = max(k-cnt,0)
    cycle = visited[last]-visited[j]+1
    answ += (answ-d[j])*(k1//cycle)
    best[i] = max(best[i],answ)
    k1 = k1%cycle
    while(k1>0):
        j = p[j]
        answ+=c[j]
        best[i] = max(best[i],answ)
        k1-=1
    i+=1


print(max(best))

Submission status: Wrong Answer

Solution code:
import sys


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

def smax(b,nn):
    cc=0
    bmax9=-10**30
    for i in range(nn):
#       print(b,p[b])
       b=p[b]
       cc+=c[p[b]]
#       print(i,cc,bmax9)
       bmax9=max(bmax9,cc)
    return bmax9,cc

if k<=n:
    bmax=-10**30
    for st in range(n):
        bmax9,cc=smax(st,k)
        bmax=max(bmax,bmax9)
    print(bmax)
    sys.exit()
    
bmax=-10**30
for st in range(n):
    cc=0
    b=st
    chk=[-1]*n
    chk[st]=0
    for i in range(n):
       b=p[b]
       if chk[b]>=0:
           break
       else:
           chk[b]=i+1

    ki=chk[b]+1
    kc=(i+1)-chk[b]
    k2=(k-ki)%kc+ki
#    print(st,ki,kc,k2)
    bmax1,cc1=smax(st,ki+kc)
    bmax0,cc0=smax(st,ki)
    ccc=cc1-cc0
    if ccc<=0:
        bmax9,cc=smax(st,k2)
    else:
        bmax9,cc=smax(st,k2)
        bmax9+=ccc*((k-ki)//kc)

    bmax=max(bmax,bmax9)
print(bmax)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!

n,k=map(int,input().split())

p=list(map(lambda x:int(x)-1,input().split()))
c=list(map(int,input().split()))

lps=[]
vtd=[False]*n
for i in range(n):
    if vtd[i]:continue
    now=p[i]
    vtd[now]=True
    vc=set()
    vc.add(now)
    while now!=i:
        now=p[now]
        vtd[now]=True
        vc.add(now)
    point=0
    for v in vc:
        point+=c[v]
    lps.append((list(vc),point))
# print(lps)
anslist=[]
for lp in lps:
    loop=lp[0]
    ls=len(loop)
    point=lp[1]
    if point<=0:
        ans=max(c)
        for first in loop:
            tmp=0
            now=first
            for j in range(min(k,ls)):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans)
    if point>0:
        ans=max(c)
        for first in loop:
            tmp=0
            now=first
            for j in range(k%ls+1):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans+point*(k//ls-1))
print(max(anslist))

Submission status: Wrong Answer

Solution code:
def li():
    return [int(x) for x in input().split()]

N, K = li()
P = [0] + li()
C = [0] + li()

def get_cycle(start_i):
    cycle = []
    i = start_i
    while True:
        i = P[i]
        if i == start_i:
            break
        cycle.append(i)
    cycle.append(start_i)
    return cycle

def get_cycle_scores(cycle):
    score = 0
    scores = [score]
    for i in cycle:
        score += C[i]
        scores.append(score)
    return scores

max_scores = []
for start_i in range(1,N+1):
    cycle = get_cycle(start_i)
    scores = get_cycle_scores(cycle)
    # 1cycle以下の場合は全て調べればよし
    if K < len(cycle):
        max_score = max(scores[move] for move in range(1, K+1))
        print(max_score)
        exit()
    # 1サイクルの長さ
    cycle_len = len(cycle)
    # 1サイクルごとのスコア
    score_per_cycle = scores[cycle_len]
    # ラスト1サイクルのスコア
    scores_last_cycle = []
    # 最後の1cycleの値を調べる
    for move in range(K-cycle_len+1, K+1):
        # 何周したか
        loop_cnt = move // cycle_len
        # あまり
        rest_move = move % cycle_len
        # スコア = 1周ごとのスコア * 何周したか + あまり
        score = loop_cnt * score_per_cycle + scores[rest_move]
        scores_last_cycle.append(score)

    max_scores.append(max(scores_last_cycle))

print(max(max_scores))

Submission status: Wrong Answer

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

ans = -float('inf')

for i in range(n): #start
    start = i
    now = start
    total = 0
    ls = [0]

    for j in range(1, k+1):
        now = pn[now]-1
        total += cn[now]
        ans = max(ans, total)
        ls.append(total)
        if now == start:
            rp = j
            break
    else:
        continue

    if total <= 0:
        continue
    else:
        if k % rp == 0:
            ans = max(ans, total * (k//rp))
        else:
            s = k % rp
            ans2 = total * (k//rp) + max(ls[:s+1])
            ans = max(ans, ans2)
print(ans)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!
# ng

n,k=map(int,input().split())

p=list(map(lambda x:int(x)-1,input().split()))
c=list(map(int,input().split()))

lps=[]
vtd=[False]*n
for i in range(n):
    if vtd[i]:continue
    now=p[i]
    vtd[now]=True
    vc=set()
    vc.add(now)
    while now!=i:
        now=p[now]
        vtd[now]=True
        vc.add(now)
    point=sum(c[v] for v in vc)
    lps.append((list(vc),point))
#print(lps)
anslist=[]
for lp in lps:
    loop=lp[0]
    ls=len(loop)
    point=lp[1]
    if point<=0:
        ans=max(c)
        for first in loop:
            tmp=0
            now=first
            for j in range(min(k,ls)):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans)
    if point>0:
        ans=max(c)
        for first in loop:
            tmp=0
            now=first
            for j in range(k%ls):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans+point*(k//ls-1))
print(max(anslist))

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal

INF = 1 << 100


def run():
    N, K = map(int, sysread().split())
    P = list(map(int, sysread().split()))
    C = list(map(int, sysread().split()))
    P = [p-1 for p in P]

    loops = []
    checked = [0] * N
    loop = [0]
    for i in range(N):
        current = i
        while True:
            if not checked[current]:
                checked[current] = 1
                loop.append(C[current])
                current = P[current]
            else:
                if len(loop) == 1:break
                loops.append(loop)
                loop = [0]
                break
    loopSums = []
    for loop in loops:
        val = 0
        tmp = []
        for l in loop:
            val += l
            tmp.append(val)
        loopSums.append(tmp)
    #print(loops)
    #print(loopSums)
    ans = -INF
    for loop, loopSum in zip(loops, loopSums):
        for i in range(1, len(loop)):
            val = 0
            if loopSum[-1] <= 0 or len(loop)-1 > K:
                j = i
                max_val = -INF
                iter = 0
                done = False
                while iter <= K:
                    if j >= len(loop):j=0
                    if (i != j and j) or done:
                        val += loop[j]
                        max_val = max(val, max_val)
                    j += 1
                    if not j ==1:
                        iter += 1
                    if done : break
                    if i == j: done = True
                ans = max(ans, max_val)
                continue


            rest = K
            #if K <= len(loop) - i - 1:
            #    val += loopSum[i + K - 1] - loopSum[i]
            #    ans = max(ans, val)
            #    continue
            rest -= len(loop) - i - 1
            val += loopSum[-1] - loopSum[i]
            val += (rest // (len(loop)-1)) * loopSum[-1]
            rest = rest % (len(loop) - 1)
            val += max(loopSum[0:rest+1])
            ans = max(ans, val)

    print(ans)

if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
def main():
    n, ko = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    scores_all = set()
    for k1 in range(n):
        scores = []
        kita = [0] * n
        cnt = ko
        koko = k1
        kita[koko] = cnt
        cycle_long = n
        cnt -= 1
        koko = p[koko] - 1
        while cnt:
            if kita[koko]:
                cycle_long = kita[koko] - cnt
                scores.append(c[koko])
                break
            else:
                scores.append(c[koko])
                kita[koko] = cnt
                koko = p[koko] - 1
                cnt -= 1
        scores_a = tuple(accumulate(scores))
        if cnt:
            if scores_a[-1] > 0:
                kaisuu = ko // cycle_long
                s = scores_a[-1] * kaisuu
                amari = ko % cycle_long
                if amari:
                    s += max(scores_a[:amari])
                scores_all.add(s)
            else:
                scores_all.add(max(scores_a))
        else:
            scores_all.add(max(scores_a))

    print(max(scores_all))

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 start in range(N):
  position = start
  score_tmp = []
  for k in range(K):
    position = P[position] - 1
    score_tmp.append(C[position])
    score.append(sum(score_tmp))
 
    if position == start:
      score_per_round = sum(score_tmp)
      length_per_round = len(score_tmp)
      nrounds = K // length_per_round
      mod = k % length_per_round
      
      if score_per_round > 0:
        for i_mod in range(mod):
          score.append(nrounds * score_per_round + sum(score_tmp[:i_mod]))
      else:
        for i_round in range(nrounds+1):
          score.append(sum(score_tmp[:i_round+1]))

      break

print(max(score))

Submission status: Wrong Answer

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

check = [False] * (N+10)
roop = []

for i in range(1, N+1):
    tmp = []
    s = P[i-1]
    while True:
        if check[s]:
            break
        check[s] = True
        tmp.append(s)
        s = P[s-1]
    if len(tmp) > 0:
        roop.append(tmp)

ans = -10**18
for li in roop:
    SUM = 0
    for i in li:
        SUM += C[i-1]
    length = len(li)
    try_roop = K//length
    amari = K%length
    if amari == 0:
        try_a = length
    else:
        try_a = amari
    for j in range(length):
        tmp = -10**18
        s = li[j]
        tmp1 = 0
        for k in range(try_a):
            tmp1 += C[s-1]
            tmp = max(tmp, tmp1)
            s = P[s-1]
        
        if SUM >= 0:
            ans = max(ans, SUM*try_roop + tmp)
        elif try_roop >= 1:
            ans = max(ans, SUM, tmp)
        else:
            ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys


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

def smax(b,nn):
    cc=0
    bmax9=-10**20
    for i in range(nn):
#       print(b,p[b])
       b=p[b]
       cc+=c[p[b]]
#       print(i,cc,bmax9)
       bmax9=max(bmax9,cc)
    return bmax9,cc

if k<=n:
    bmax=-10**20
    for st in range(n):
        bmax9,cc=smax(st,k)
        bmax=max(bmax,bmax9)
    print(bmax)
    sys.exit()
    
bmax=-10**20
for st in range(n):
    cc=0
    b=st
    chk=[-1]*n
    chk[st]=0
    for i in range(n):
       b=p[b]
       if chk[b]>=0:
           break
       else:
           chk[b]=i+1

    ki=chk[b]+1
    kc=(i+1)-chk[b]
    k2=(k-ki)%kc+ki
#    print(st,ki,kc,k2)
    bmax1,cc1=smax(st,ki+kc)
    bmax0,cc0=smax(st,ki)
    ccc=cc1-cc0
    if ccc<=0:
        bmax9,cc=smax(st,k2)
    else:
        bmax9,cc=smax(st,k2)
        bmax9+=ccc*((k-ki)//kc)

    bmax=max(bmax,bmax9)
print(bmax)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    N, K = [int(x) for x in input().split()]
    P = [int(x) - 1 for x in input().split()]
    C = [int(x) for x in input().split()]

    ans = max(C)
    for i in range(N):
        next = P[i]
        cnt = 0
        tmp = 0

        while True:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if cnt == K or next == i:
                break
            next = P[next]

        if cnt == K:
            continue

        q = K // cnt
        r = K % cnt
        next = P[i]
        tmp *= q
        ans = max(ans, tmp)
        while r > 0:
            tmp += C[next]
            ans = max(ans, tmp)
            next = P[next]
            r -= 1
    print(ans)


if __name__ == '__main__':
    main()