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:
# 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):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans+point*(k//ls))
print(max(anslist))

Submission status: Wrong Answer

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

P = [p-1 for p in list(map(int, input().split()))]
C = list(map(int, input().split()))

INF = float('inf')

max_points = []
for i in range(N):
    max_point = -INF
    visit = [0] * N
    visit[i] = 1
    S = [0]
    pos = P[i]
    loop = 0  # P は順列なので、すでにvisitした点に戻ったとき、loopが位数となる
    while True:
        if visit[pos] == 0:
            visit[pos] = 1
            S.append(S[loop] + C[pos])
            pos = P[pos]
            loop += 1
        else:
            S.append(S[loop] + C[pos])
            pos = P[pos]
            loop += 1
            break

    loop_point = S[loop]
    # print(loop_point)
    # print(i, visit)
    if loop_point > 0:
        max_point = loop_point * (K // loop)
        resi = K % loop
        if resi:
            max_point += max(S[:resi+1])
    else:
        if loop < K:
            max_point = max(S[1:K+1])
        else:
            max_point = max(S[1:loop])

    max_points.append(max_point)

print(max(max_points))

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):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans+point*(k//ls))
print(anslist)

Submission status: Wrong Answer

Solution code:
import math

def split_to_loops(G):
    # G[i]: i の次の頂点(0 <= i <= |G|-1) を格納しているリストがあるとき、
    # ループ単位にリストを分割する。
    # ex) G = [1, 3, 4, 0, 2]
    # => "0 -> 1 -> 3 -> 0" というループと
    #    "2 -> 4 -> 2" というループがある
    # このメソッドでは、[[0,1,3],[2,4]]が返される

    loops = []
    _all = set(range(len(G)))

    while _all:
        s = _all.pop()
        loop = [s]
        v = G[s]
        while v != s:
            _all.remove(v)
            loop.append(v)
            v = G[v]

        loops.append(loop)

    return loops

def split_to_positive(A):
    # Aのリストを、正の数が連続している部分に分割する
    # 端っこは繋がっているとみなす
    # ex) A = [1, -2, 4, 3, -1, 2, 6, 4, 5, -3, 2]
    # => [[4, 3], [2, 6, 4, 5], [2, 1]]
    positives = []
    l = []
    for a in A:
        if a > 0:
            l.append(a)
        else:
            if l:
                positives.append(l)
            l = []

    if l:
        positives.append(l)
    
    # 途中に負の数が混じってて、端っこが両方正なら、端っこのリストをつなげる
    # （上の例でいう2と1を一つのリストにする）
    if A[0] > 0 and A[-1] > 0 and len(positives) >= 2:
        positives[-1] += positives[0]
        del positives[0]

    return positives

def find_max_continued(A, n):
    # A 内で連続した1個以上n個以内の領域の合計の最大値を見つける
    # ex) A = [-2, 4, 3, -1, 2, 6, 4, 5, -3], n = 3
    #       => [6, 4, 5] の合計 =15 が最大
    # ex) A = [-2, 4, 3, -1, 2, 6, -4, 5, -3], n = 3
    #       => [2, 6] の合計 =8 が最大
    # ex) A = [-2, -4, -3, -1, -2, -6, -4, -5, -3], n = 3
    #       => [-1] の合計 =-1 が最大


    # 方針：正の値が連続している部分を抜き出す
    # => [[4, 3], [2, 6, 4, 5]]

    positives = split_to_positive(A)
    # print(f'{positives=}')
    # もしAの中に正の数がないなら、A内の最大値が返すべき値
    if len(positives) == 0:
        return max(A)

    # それぞれの連続部分で、n個以内の連続部分の最大値を探す
    _max = 0
    for P in positives:
        _sum = sum(P[:n])
        _max = max(_max, _sum)
        L = len(P)
        # 連続領域がn個以上の場合、左からn個の合計を計算した後、
        # 領域を右にずらしながら合計を計算することで、O(L) で計算できる 
        for i in range(n, L):
            _sum += P[i] - P[i-n]
            _max = max(_max, _sum)

    return _max

def find_max_in_one_loop(loop, K, C):
    # loopにおける1回以上K回以内の移動でのスコアの最大値を見つける
    L = len(loop)
    loop_c = [C[v] for v in loop] # ループに登場するマスのスコアのリスト
    # print(f'{loop_c=}')

    # 一周したときのスコア
    sum_1_loop = sum(loop_c)
    # print(f'{loop_c=}, {sum_1_loop=}')

    if sum_1_loop < 0:
        # 一周したときに負になるようなら、ループしないほうがいい
        return find_max_continued(loop_c, min(K, L))
    else:
        # 一周以上移動できない場合
        if K < L:
            return find_max_continued(loop_c, K)

        # 一周以上移動できる場合
        # できるだけループしたほうがいい

        n_loops = K // L # ループできる回数

        # ただし、スコアが [1 1 1 -2] のようになっている場合、
        # 1周するより負の数を避けて途中で終了したほうがいいので、
        # 一旦わざとループできる回数から1周分減らしておく
        n_loops -= 1
        
        score = sum_1_loop * n_loops
        K -= n_loops * L # 残りの移動回数 (L <= K < 2*L)

        # 一周未満の時のスコアの最大値
        score_no_loop = find_max_continued(loop_c, L)
        # 一周してさらにK-L回以内で移動するときのスコア
        score_loop = sum_1_loop
        if K != L:
            score_loop += find_max_continued(loop_c, K - L)
        # 最後、一周しないほうがいいか、一周したほうがいいか、スコアの大きいほうを選ぶ
        score += max(score_no_loop, score_loop)
        return score

def main():
    N, K = map(int, input().split())
    # P は番号を1引くことで配列で扱いやすくする
    P = list(map(lambda x: int(x)-1, input().split()))
    C = list(map(int, input().split()))

    # ループごとに分割
    # ex) P = [1, 3, 4, 0, 2]
    # => "0 -> 1 -> 3 -> 0" というループと
    #    "2 -> 4 -> 2" というループがある
    # => loops = [[0,1,3],[2,4]]
    loops = split_to_loops(P)
    # print(f'{loops=}')

    ans = -(10 ** 10)
    for loop in loops:
        # [0,1,3] などのループ単位で、1回以上K回以内の移動での最大値を見つける
        # その最大値の中からさらに最大値を見つけて、答えとする
        ans = max(ans, find_max_in_one_loop(loop, K, C))
    
    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()))
prev=[0 for i in range(N)]
for i in range(N):
    prev[P[i]-1]=i
DP=[[0 for j in range(N)] for i in range(N)]
start=[[0 for j in range(N)] for i in range(N)]
for j in range(N):
    DP[0][j]=C[j]
    start[0][j]=j
syuki=[N for j in range(N)]
for i in range(1,N):
    for j in range(N):
        DP[i][j]=DP[i-1][prev[j]]+C[j]
        start[i][j]=start[i-1][prev[j]]
        if start[i][j]==j:
            syuki[j]=min(syuki[j],i)
ite=[max(DP[syuki[j]-1][j],0) for j in range(N)]
dist=[-10000000000000000 for j in range(N)]
for i in range(N):
    if K<=N:
        for k in range(K):
            dist[i]=max(dist[i],DP[k][i])  
    elif ite[i]>0:
        for k in range(1,K%syuki[i]):
            dist[i]=max(dist[i],K//syuki[i]*ite[i]+DP[k][i]-C[i])      
    else:
        for k in range(K%syuki[i]):
            dist[i]=max(dist[i],DP[k][i])
print(max(dist))

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()))
 
ans = max(c)
for i in range(n):
    curr = 0
    score = [0]
    posi = i
    while p[posi] != i:
        posi = p[posi]
        curr += c[posi]
        score.append(curr)
    cycle_score = score[-1] + c[i]
    cycle_len = len(score)
    
    num = k // cycle_len
    rest = k % cycle_len
    rest_max = max(c)
    for j in range(1,rest+1):
        rest_max = max(rest_max, score[j])
    if k > cycle_len:
        ans = max(ans, max(score), max(score)+cycle_score*(num-1), rest_max+cycle_score*num)
    elif k <= cycle_len:
        ans = max(ans, rest_max)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P, C = [list(map(int, input().split())) for _ in range(2)]
c = [1] * N
m = [[0] * (N+1) for i in range(N)]
for i in range(N):
    m[i][1] = (C[P[i]-1])
ans = max(C)
for i in range(N):
    j = i
    while P[j]-1 != i:
        j = P[j]-1
        c[i] += 1
        m[i][c[i]] = m[i][c[i]-1] + C[P[j]-1]
    if m[i][c[i]] > 0:
        if K%c[i] > 0:
            ans = max(ans, m[i][c[i]] * (K//c[i]) + max(m[i][1:K%c[i]+1]))
        else:
            ans = max(ans, m[i][c[i]] * (K//c[i]))
    else:
        ans = max(ans, max(m[i][1:min(c[i],K)+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()))
m=min(C)
score_max=m
for L in range(n):
  score=0
  d=[0]*n
  r=0
  d[L]=1
  for i in range(k):
    r+=1
    L=P[L]-1
    score+=C[L]
    score_max=max(score,score_max)
    if d[L]==0:
      d[L]=1
    else:
      roop=k//r
      score = score*roop
      score_max=max(score,score_max)
      h=k%r
      for j in range(h):
        L=P[L]-1
        score+=C[L]
        score_max=max(score,score_max)
      break
print(score_max)

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,
      score * (loops - 1) + max(scores)
    )
  else:
    score = max(scores)
  ans = max(ans, score)

print(ans)

Submission status: Wrong Answer

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

wa = []
checked = []
for i in range(n):
    if i not in checked:
        index = i
        s = c[index]
        w = [0, c[index]]
        checked.append(index)
        index = p[index] - 1
        while index != i:
            s += c[index]
            w.append(s)
            checked.append(index)
            index = p[index] - 1

        large = [[] for x in range(len(w))]
        for ii in range(1, len(w)):
            for j in range(len(w)-ii):
                large[ii].append(w[ii+j] - w[j])
                if j != 0 and ii+j < len(w):
                    large[len(w)-1-ii].append(s - (w[ii+j] - w[j]))
        #print(large)

        for j in range(1, len(large)):
            large[j] = max(large[j])
        #print(large)
        large[0] = 0
        if len(w)-1 >= k:
            wa.append(max(large[1:k+1]))
        if len(w)-1 < k and large[-1] > 0:
            wa.append(max((k // (len(w)-1)) * large[-1] + max(large[:(k % (len(w)-1))+1]), max(large[1:])))
        else:
            wa.append(max(large[1:]))

print(max(wa))

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
m=min(C)
score_max=m
for L in range(n):
  score=0
  d=[0]*n
  r=0
  d[L]=1
  for i in range(k):
    r+=1
    L=P[L]-1
    score+=C[L]
    score_max=max(score,score_max)
    if d[L]==0:
      d[L]=1
    elif score<0:
      break
    else:
      roop=k//r
      score = score*roop
      score_max=max(score,score_max)
      h=k%r
      for j in range(h):
        L=P[L]-1
        score+=C[L]
        score_max=max(score,score_max)
      break
print(score_max)

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((vc,point))
print(lps)
# loop_cost=[]
# for lp in lps:
#     point=0
#     for j in lp:
#         point+=c[j]
#     loop_cost.append((lp,point))
# print(loop_cost)

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()))
 
ans = max(c)
for i in range(n):
    curr = 0
    score = [0]
    posi = i
    while p[posi] != i:
        posi = p[posi]
        curr += c[posi]
        score.append(curr)
    cycle_score = score[-1] + c[i]
    cycle_len = len(score)
    
    num = k // cycle_len
    rest = k % cycle_len
    rest_max = 0
    for j in range(rest+1):
        rest_max = max(rest_max, score[j])
    if k >= cycle_len:
        ans = max(ans, max(score), max(score)+cycle_score*(num-1), rest_max+cycle_score*num)
    elif k < cycle_len:
        ans = max(ans, rest_max)
print(ans)

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)
    lps.append(list(vc))

loop_cost=[]
for lp in lps:
    point=0
    for j in lp:
        point+=c[j]
    loop_cost.append((lp,point))
print(loop_cost)

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)
    if remaining:
      score = max(
        score * loops + max(0, max(scores[:remaining])),
        score * (loops - 1) + max(scores)
      )
    else:
      score = max(score * loops, *scores)
  else:
    score = max(scores)
  ans = max(ans, score)

print(ans)

Submission status: Wrong Answer

Solution code:
import math
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Cs = list(map(int, input().split()))

unions = []
checked_num = set()
for i in range(N):
    num = i
    union_set = []
    while num not in checked_num:
        checked_num.add(num)
        union_set.append(Cs[num])
        num = Ps[num]-1
        if num == i:
            unions.append(union_set)
            break

final_max_score = -math.inf

for num_set in unions:
    length = len(num_set)
    count = 0
    if K > length:
        num_sum = sum(num_set)
        remainder = K%length
        if num_sum > 0:
            count = K//length
            num_sum_count = num_sum*count
            num_sum_count2 = num_sum*(count-1)
        K = length
    for k in range(1, K+1):
        #print(k)
        #print(num_set)
        max_score = 0
        for i in range(length):
            score = 0
            sum_list = num_set[i:k+i]
            if i+k-length > 0:
                sum_list += num_set[0:i+k-length]
            for item in sum_list:
                if item < 0:
                    break
                score += item
            else:
                if score > max_score:
                    max_score = score
        if (count > 0 and k <= remainder):
            max_score = max_score + num_sum_count
        elif (count > 0 and k > remainder):
            max_score = max_score + num_sum_count2
            #print(max_score)
        if max_score > final_max_score:
            final_max_score = max_score
print(final_max_score)

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)
    if remaining:
      score = max(
        score * loops + max(0, max(scores[:remaining])),
        score * (loops - 1) + max(scores[remaining - 1:])
      )
    else:
      score = max(score * loops, *scores)
  else:
    score = max(scores)
  ans = max(ans, score)

print(ans)

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

lp=[]
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)
    print(vc)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
prev=[0 for i in range(N)]
for i in range(N):
    prev[P[i]-1]=i
DP=[[0 for j in range(N)] for i in range(N)]
start=[[0 for j in range(N)] for i in range(N)]
for j in range(N):
    DP[0][j]=C[j]
    start[0][j]=j
syuki=[N for j in range(N)]
for i in range(1,N):
    for j in range(N):
        DP[i][j]=DP[i-1][prev[j]]+C[j]
        start[i][j]=start[i-1][prev[j]]
        if start[i][j]==j:
            syuki[j]=min(syuki[j],i)
ite=[max(DP[syuki[j]-1][j],0) for j in range(N)]
dist=[-10000000000000000 for j in range(N)]
for i in range(N):
    if K==N:
        for k in range(K):
            dist[i]=max(dist[i],DP[k][i])  
    elif ite[i]>0:
        for k in range(1,K%syuki[i]+1):
            dist[i]=max(dist[i],K//syuki[i]*ite[i]+DP[k][i]-C[i])      
    else:
        for k in range(K%syuki[i]):
            dist[i]=max(dist[i],DP[k][i])
print(max(dist))

Submission status: Wrong Answer

Solution code:
def f(x):
  D=[-1]*(N+1)
  D[x]=0
  S=[None]*(N+1)
  S[x]=0
  ima=x+0
  for count in range(1, K+1):
    if D[P[ima]]<0:
      D[P[ima]]=count
      S[P[ima]]=S[ima]+C[P[ima]]
      ima=P[ima]+0
    else:
      if S[ima]+C[P[ima]]>S[P[ima]]:
        isshu=count-D[P[ima]]
        atonanshu=(K-count)//isshu
        atonanho=(K-count)%isshu+1
        agatta=S[ima]+C[P[ima]]-S[P[ima]]
        S[P[ima]]=S[ima]+C[P[ima]]+agatta*atonanshu
        D[P[ima]]=D[ima]+1
        
        ima=P[ima]+0
        for _ in range(atonanho):
          S[P[ima]]=S[ima]+C[P[ima]]
          D[P[ima]]=D[ima]+1
          ima=P[ima]+0
      break
      
  if D[x]==0:
    S[x]=None
  return max([s for s in S if s is not None])

N, K=map(int, input().split())
P=[None]+list(map(int, input().split()))
C=[None]+list(map(int, input().split()))

print(max([f(x) for x in range(1, N+1)]))

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(50000)
N,K= [int(v) for v in input().split()]
P = [int(v) - 1 for v in input().split()]
C = [int(v) for v in input().split()]

visited = [True for _ in range(N)]
cycle = []


ans = -float('inf')
for sn in range (N):
    cost = [C[sn]]
    nn = P[sn]
    while True:
        if sn == nn:
            break
        cost.append(C[nn])
        nn = P[nn]

    total = sum(cost)
    l = len(cost)

    t = 0
    for i in range(l):
        t += cost[i]
        if i+1 > K: break
        now = t
        if total > 0:
            e = (K-i-1)/l
            now += total * e
        ans = max(ans,now)


print(int(ans))

Submission status: Wrong Answer

Solution code:
def f(x):
  D=[-1]*(N+1)
  D[x]=0
  S=[None]*(N+1)
  S[x]=0
  ima=x+0
  for count in range(1, K+1):
    if D[P[ima]]<0:
      D[P[ima]]=count
      S[P[ima]]=S[ima]+C[P[ima]]
      ima=P[ima]+0
    else:
      if S[ima]+C[P[ima]]>S[P[ima]]:
        isshu=count-D[P[ima]]
        atonanshu=(K-count)//isshu
        atonanho=(K-count)%isshu-1
        agatta=S[ima]+C[P[ima]]-S[P[ima]]
        S[P[ima]]=S[ima]+C[P[ima]]+agatta*atonanshu
        D[P[ima]]=D[ima]+1
        
        ima=P[ima]+0
        for _ in range(atonanho):
          S[P[ima]]=S[ima]+C[P[ima]]
          D[P[ima]]=D[ima]+1
          ima=P[ima]+0
      break
      
  if D[x]==0:
    S[x]=None
  return max([s for s in S if s is not None])

N, K=map(int, input().split())
P=[None]+list(map(int, input().split()))
C=[None]+list(map(int, input().split()))

print(max([f(x) for x in range(1, N+1)]))

Submission status: Wrong Answer

Solution code:
def calc_max(p):
    lp=p
    l=[]
    S=0
    max_range=0
    tmpM=0
    for _ in range(K):
        l.append(C[p])
        S+=C[p]
        if tmpM<S:
            tmpM=S
            max_range=_+1
        p=P[p]
        if p==lp:
            break
    if S>0:
        t=len(l)
        tmpK=K-max_range
        return S*(tmpK//t)+tmpM
    else:
        return tmpM

N,K=map(int,input().split())
P=list(map(lambda x:int(x)-1,input().split()))
C=list(map(int,input().split()))
ans=max(map(calc_max,range(N)))
if ans==0:
    print(max(C))
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
(n,k),p,c  = [list(map(int, s.split())) for s in open(0)]

pset = set(p)
ans = c[0]
for x in range(1,n+1):
    _sum = [0 for _ in range(2*n)]
    num = 0
    while x in pset:
        pset.remove(x)
        _sum[num + 1] = _sum[num] + c[x-1]
        x = p[x-1]
        num += 1
    if num > 0:
        for i in range(1,num):
            _sum[num + i] += _sum[num] + _sum[i]
        # i == 0
        tmp = _sum[num] * (k//num)
        if tmp > ans:
            ans = tmp
        for i in range(1, min(k+1,num)):
            base = max(0, _sum[num]) * ((k-i)//num)
            for j in range(num):
                tmp = _sum[j+i] - _sum[j] + base
                if tmp > ans:
                    ans = tmp
print(ans)

Submission status: Wrong Answer

Solution code:
mod=1000000007
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))

dp=[[ -mod for i in range(k+1)]for j in range(n)]

for i in range (n):
    dp[i][k]=c[i]

ans=-mod

for i in range (n):
    for j in range(k,0,-1):
        np=p[i]-1
        dp[np][j-1]=dp[i][j]+c[np]
        ans=max(ans,dp[i][j],dp[np][j-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()))
ls = [0]*n
z = 0
l = 0
lv = 0

for i in range(n):
    v = 0
    tmp = i
    cl =[]
    for j in range(n):
        if j <= k-1:
            tmp = p[tmp]-1
            v += c[tmp]
            if ls[j] < v or ls[j]==0:
                ls[j] = v
            if tmp in cl:
                if lv < v - c[tmp]:
                    l = len(cl)
                    lv = v - c[tmp]
                break
            cl.append(tmp) 

if k >= n and l > 0:
    z = lv * int(k/l)
    k = k%l
elif k >= n and l == 0:
    z = sum(c) * int(k/n)
    k = k%n

#print(z,ls)

if z > 0 and k != 0:
    print(z+max(ls[:k]))
elif z < 0 and k != 0:
    print(max(ls[:k]))
else:
    print(max(ls))

Submission status: Wrong Answer

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

import sys
import pprint

sys.setrecursionlimit(10 ** 6)

class Logger:
	def __init__(self, debug):
		self.debug = debug
	def print(self, *args):
		if self.debug:
			pprint.pprint(args)

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():
	log = Logger(0)
	n, k = map(int, sys.stdin.readline().split())
	p = list(map(int, sys.stdin.readline().split()))
	c = list(map(int, sys.stdin.readline().split()))
	uf = UnionFind(n)
	max_score = -float("inf")
	for i in range(n):
		uf.union(p[i] - 1, i)
	log.print(uf.all_group_members())
	for i in range(n):
		cnt = k
		score = 0
		loop = uf.members(p[i]-1)
		log.print(loop)
		if k >= len(loop):
			here = i
			loopsum = 0
			for j in range(len(loop)):
				here = p[here] - 1
				loopsum += c[here]
			if loopsum > 0:
				score += loopsum * (k // len(loop))
				cnt %= len(loop)
		tmp_max_score = -float("inf")
		here = i
		for j in range(len(loop)):
			if j >= cnt:
				tmp_max_score = max(tmp_max_score, score)
				break
			here = p[here] - 1
			score += c[here]
			log.print(here, score)
			tmp_max_score = max(tmp_max_score, score)
		
		log.print(tmp_max_score)
		max_score = max(tmp_max_score, max_score)
	print(max_score)




	


main()

Submission status: Wrong Answer

Solution code:
import math
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Cs = list(map(int, input().split()))

unions = []
checked_num = set()
for i in range(N):
    num = i
    union_set = []
    while num not in checked_num:
        checked_num.add(num)
        union_set.append(Cs[num])
        num = Ps[num]-1
        if num == i:
            unions.append(union_set)
            break

final_max_score = -math.inf

for num_set in unions:
    length = len(num_set)
    count = 0
    if K > length:
        num_sum = sum(num_set)
        remainder = K%length
        if num_sum > 0:
            count = K//length
            num_sum_count = num_sum*count
            num_sum_count2 = num_sum*(count-1)
        K = length
    for k in range(1, K+1):
        #print(k)
        #print(num_set)
        score = 0
        max_score = -math.inf
        for i in range(length):
            score = 0
            score += sum(num_set[i:k+i])
            if i+k-length > 0:
                score += sum(num_set[0:i+k-length])
            if score > max_score:
                max_score = score
        if (count > 0 and k <= remainder):
            max_score = max_score + num_sum_count
        elif (count > 0 and k > remainder):
            max_score = max_score + num_sum_count2
            #print(max_score)
        if max_score > final_max_score:
            final_max_score = max_score
print(final_max_score)

Submission status: Wrong Answer

Solution code:
def calc_max(p):
    p=p
    l=[]
    S=0
    max_range=0
    tmpM=0
    for _ in range(K):
        l.append(C[p])
        S+=C[p]
        if tmpM<S:
            tmpM=S
            max_range=_
        p=P[p]
        if p==P:
            break
    if S>0:
        t=len(l)
        tmpK=K-max_range
        return S+(tmpK//t)*sum(l)
    else:
        return S

N,K=map(int,input().split())
P=list(map(lambda x:int(x)-1,input().split()))
C=list(map(int,input().split()))
ans=max(map(calc_max,range(N)))
if ans==0:
    print(max(C))
else:
    print(ans)