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 = list(map(int, input().split()))
P = list(map(lambda x: int(x) - 1, input().split()))
C = list(map(int, input().split()))

step_score = [0] * N
max_score = -1 * float('inf')

for start_pos in range(N):
    pos = start_pos
    loop_num = 0
    loop_sum = 0
    step = 0
    while (step < K and step < N):
        pos = P[pos]
        loop_sum += C[pos]
        step_score[step] = loop_sum
        step += 1
        if pos == start_pos:
            break
    loop_num = step
    step_max_score = max(step_score)
    if K // loop_num > 0:
        if K % loop_num != 0:
            step_max_score = max(
                step_max_score,
                max(step_score[:(K % loop_num)]) + loop_sum * (K // loop_num)
            )
        else:
            step_max_score = max(
                step_max_score,
                max(step_score) + loop_sum * (K // loop_num)
            )
    if K // loop_num > 1:
        step_max_score = max(
            step_max_score,
            max(step_score) + loop_sum * (K // loop_num - 1)
        )
    max_score = max(step_max_score, max_score)
    # print(start_pos, step_max_score, max(step_score), loop_sum, loop_num)

print(max_score)

Submission status: Wrong Answer

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

step_score = [0] * N
max_score = -1 * float('inf')

for start_pos in range(N):
    pos = start_pos
    loop_num = 0
    loop_sum = 0
    step = 0
    while (step < K and step < N):
        pos = P[pos]
        loop_sum += C[pos]
        step_score[step] = loop_sum
        step += 1
        if pos == start_pos:
            break
    loop_num = step
    step_max_score = max(step_score)
    if K // N > 0:
        if K % loop_num != 0:
            step_max_score = max(
                step_max_score,
                max(step_score[:(K % loop_num)]) + loop_sum * (K // loop_num)
            )
        else:
            step_max_score = max(
                step_max_score,
                max(step_score) + loop_sum * (K // loop_num)
            )
    if K // N > 1:
        step_max_score = max(
            step_max_score,
            max(step_score) + loop_sum * (K // loop_num - 1)
        )
    max_score = max(step_max_score, max_score)
    # print(start_pos, step_max_score, max(step_score), loop_sum, loop_num)

print(max_score)

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 > 0:
            idx = pl[idx]-1
            if not flag:
                ith += 1
                if vis[idx] != 0:
                    flag = True
                    cv = m-(val[idx]-cl[idx])
                    cn = ith-vis[idx]
                    rest = k//cn
                    if rest:
                        m += cv*rest
                        M = max(M, m)
                        k -= cn*rest
                else:
                    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:
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])

    print(res)

Submission status: Wrong Answer

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

points = list()
for i in range(N):
    sum = 0
    next = P[i]
    result = list()
    for j in range(N):
        sum += C[next]
        result.append(sum)
        if next == i:
            break
        next = P[next]
    points.append(result)

ans = -int(1e18)

for i in range(len(points)):
    cir = len(points[i])
    cir_point = points[i][cir-1]

    if K <= cir:
        for j in range(K):
            ans = max(ans, points[i][j])
    else:
        if cir_point > 0:
            for j in range(K % cir):
                ans = max(ans, points[i][j] + (K // cir) * cir_point)

        for j in range(cir):
            ans = max(ans, points[i][j])

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

l=[]
for i in range(n):
    l.append([p[i],c[i],True])
jun=[]
ju=[]
o=0
for i in l:
    if i[2]:
        ju=[]
        i[2]=False
        o=i[0]
        ju.append(i[1])
        while l[o-1][2]:
            ju.append(l[o-1][1])
            l[o-1][2]=False
            o=l[o-1][0]
        jun.append(ju+ju)
out=min(c)
for x in jun:
    m=min(x)
    sav=0
    n=int(len(x)/2)
    mi=n-1
    if sum(x)>0:
        sav=sum(x)/2*(k//n)
        mi=k%n
    for i in range(0,n):
        f=0
        for j in range(0,min(n,mi)):
            f+=x[i+j]
            if f>=m:
                m=f
    sav+=m
    if sav>=out:
        out=sav
print(int(out))

Submission status: Wrong Answer

Solution code:
import itertools
N, K = [int(_) for _ in input().split()]
P = [int(_) - 1 for _ in input().split()]
C = [int(_) for _ in input().split()]
ans = -float('inf')
for start in range(N):
    now = start
    scores = []
    while True:
        scores += [C[now]]
        now = P[now]
        if now == start:
            break
    scores = list(itertools.accumulate(scores))
    v1 = max(scores[:K])
    cycles, residue = divmod(K, len(scores))
    v2 = -float('inf')
    if cycles:
        v2 = scores[-1] * cycles + max([0] + scores[:residue])
    ans = max([ans, v1, v2])
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()))
g = [[0]*(n) for _ in range(n)]
A = [n]*n
for i in range(n):
    tmp = 0
    idx = i
    cnt = 0
    set_ =set()
    while cnt<n:
        if C[idx] not in set_:
            tmp += C[idx]
            set_.add(C[idx])
            g[i][cnt] = tmp
            idx = P[idx]-1
            cnt += 1
        else:
            p = len(set_)
            A[i] = p
            break
ans = -float('inf')

for i in range(n):
    v,w = k//A[i],k%A[i]
    if A[i]<k:
        if g[i][A[i]-1]<=0:
            val = max(g[i][:A[i]])
        else:
            val1 = (v-1)*g[i][A[i]-1]
            val1 += max(g[i][:A[i]])
            val2 = v*g[i][A[i]-1]
            if w!=0:
                val2 += max(0,max(g[i][:w]))
            val = max(val1,val2)
    else:
        val = max(g[i][:k])
    ans = max(ans,val)
print(ans)

Submission status: Wrong Answer

Solution code:
import itertools
N, K = [int(_) for _ in input().split()]
P = [int(_) - 1 for _ in input().split()]
C = [int(_) for _ in input().split()]
ans = -float('inf')
for start in range(N):
    now = start
    scores = []
    while True:
        scores += [C[now]]
        now = P[now]
        if now == start:
            break
    scores = list(itertools.accumulate(scores))
    v1 = max(scores[:K])
    cycles, residue = divmod(K, len(scores))
    v2 = -float('inf')
    if cycles:
        v2 = scores[-1] * cycles + max([0] + scores[:residue])
    ans = max([ans, v1, v2])
    print(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()))
g = [[0]*(n) for _ in range(n)]
A = [n]*n
for i in range(n):
    tmp = 0
    idx = i
    cnt = 0
    set_ =set()
    while cnt<n:
        if C[idx] not in set_:
            tmp += C[idx]
            set_.add(C[idx])
            g[i][cnt] = tmp
            idx = P[idx]-1
            cnt += 1
        else:
            p = len(set_)
            A[i] = p
            break
ans = -float('inf')

for i in range(n):
    v,w = k//A[i],k%A[i]
    if A[i]<k:
        if g[i][A[i]-1]<=0:
            ans = max(max(g[i][:A[i]]),ans)
        else:
            val1 = (v-1)*g[i][A[i]-1]
            val1 += max(g[i][:A[i]])
            val2 = v*g[i][A[i]-1]
            if w!=0:
                val2 += max(0,max(g[i][:w]))
            ans = max(val1,val2,ans)
    else:
        ans = max(max(g[i][:k]),ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import itertools
N, K = [int(_) for _ in input().split()]
P = [int(_) - 1 for _ in input().split()]
C = [int(_) for _ in input().split()]
ans = -float('inf')
for start in range(N):
    now = start
    scores = []
    while True:
        scores += [C[now]]
        now = P[now]
        if now == start:
            break
    scores = list(itertools.accumulate(scores))
    ans = max([ans] + scores[:K])
    cycles, residue = divmod(K, len(scores))
    ans = max(ans, scores[-1] * cycles + max([0] + scores[:residue]))
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()))
   
used=[0 for i in range(n+1)]
#1からn+1までの辺で試す
ans=-float("INF")
for i in range(1,n+1):
  #すでに探索したループは見なくて良い
  if used[i]==1:
    continue
  #今自分が居ることろをnow
  #一周のループの合計 loop_sum
  now=i
  loop=[now]
  loop_sum=0
  #連結部分を見つける
  while(1):
      loop.append(p[now])
      loop_sum+=c[p[now]]
      now=p[now]
      used[now]=1
      if p[now]==i:
          loop_sum+=c[p[now]]
          break
  #この連結なループの中で最大値を求める
  length=len(loop)
  #aから始まってk回移動
  for a in loop:
      #一周する前での最大値
      max_cost=-float("INF")
      cnt=0
      cost=0
      while cnt<length:
          cnt+=1
          a=p[a]
          cost+=c[a]
          if max_cost<cost:
            max_cost=cost
            max_num=cnt
          if cnt>=k:
              ans=max(ans,max_cost)
              break
      
      if loop_sum<=0:
        ans=max(ans,max_cost)
      else:
        ans=max(ans,max_cost+((k-max_num)//length)*loop_sum)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque
from collections import Counter
import math

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

n,k = readInts()
p = [0]+readInts()
c = [0]+readInts()

ans = -1*float("inf")
for i in range(1,n+1):
	j = p[i]
	t = [0]
	al = set()
	while j not in al:
		t.append(t[-1]+c[j])
		al.add(j)
		j = p[j]
	if t[-1]<=0:
		ans = max(ans, max(t[1:k+1]))
	else:
		kuri =(k-1)//(len(t)-1)
		s = kuri*t[-1]
		ans = max(ans, max(s,s+max(t[:k%(len(t)-1)+1])))

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
    lpc=sum(c[x] for x in lp)
    nxt=i
    lpl=len(lp)
    wks=0
    for j in range(lpl):
        nxt=p[nxt]
        wks+=c[nxt]
        ans=max(ans,(k-j-1)//lpl*lpc+wks)
        if j==k-1:
            break
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
    lpc=sum(c[x] for x in lp)
    nxt=i
    lpl=len(lp)
    wks=0
    for j in range(lpl):
        nxt=p[nxt]
        wks+=c[nxt]
        ans=max(ans,(k-j-1)//lpl*lpc+wks)
        if j>k:
            break
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()))

ans = - 10 ** 18
for i in range(1, n+1):
    base = i
    nxt = p[i]
    cnt = 0
    score = 0
    while True:
        cnt += 1
        if cnt > k:
            break
        score += c[nxt]
        ans = max(ans, score)
        #print("i = ", i, "ans = ", ans, "score = ", score)
        if nxt == base:
            break
        nxt = p[nxt]
    if cnt >= k:
        continue
    extra = k - cnt
    score_tmp = score
    nxt = p[nxt]
    nxt_tmp = nxt
    for j in range(min(extra, cnt)):
        score += c[nxt]
        ans = max(ans, score)
        #print("ans = ", ans, "score = ", score, "nxt = ", nxt, "c[nxt] = ", c[nxt])
        nxt = p[nxt]
    #print("score = ", score, "ans = ", ans)
    score = score_tmp
    nxt = nxt_tmp
    a = extra // cnt - 1
    score += score * max(a, 0)
    ans = max(ans, score)
    for j in range(extra - a * cnt):
        score += c[nxt]
        ans = max(ans, score)
        #print("ans = ", ans, "score = ", score, "nxt = ", nxt, "c[nxt] = ", c[nxt])
        nxt = p[nxt]

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np

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

P = list(map(int,input().split()))
C = list(map(int,input().split()))
C = np.array(C, dtype='int64')

mod_ = K % N
roop_num = K // N


# ループを作る
roop_list = []
total_list = []
flg_list = [False] * N
idx_i = 0
while (False in flg_list):
    idx_i = flg_list.index(False)
    init_idx = idx_i
    pos_i = -1
    roop_ = []
    total_ = 0
    max_val = -float('inf')
    val = 0
    while not(pos_i == init_idx):
        pos_i = P[idx_i] - 1
        roop_.append(pos_i)
        total_ += C[pos_i]        
        flg_list[pos_i] = True
        idx_i = pos_i
    roop_list.append(roop_)
    total_list.append(total_)


# ループの中から最善のものを選ぶ。
total_max = -float('inf')
for i in range(len(total_list)):
    if total_max < total_list[i]:
        total_max = total_list[i]
        best_roop = roop_list[i]
N_roop = len(best_roop)
roop_num = K // N_roop
mod_ = K % N_roop


# ループの残り
if roop_num >= 1:
    max_val = -float('inf')
    for i in best_roop:
        now_i = i
        val = 0
        if mod_ == 0 and total_max < 0:
            mod_ = N_roop
        for i in range(mod_):
            next_i = P[now_i] - 1
            val += C[next_i]
            now_i = next_i
            
            if max_val < val:
                max_val = val
    if total_max > 0:
        ans = max_val + total_max * roop_num
    else:
        ans = max_val
else:
    max_val = -float('inf')
    for roop in roop_list:
        for i in roop:
            now_i = i
            val = 0
            if mod_ == 0 and total_max < 0:
                mod_ = N_roop
            for i in range(mod_):
                next_i = P[now_i] - 1
                val += C[next_i]
                now_i = next_i
                
                if max_val < val:
                    max_val = val
    ans = max_val

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

import sys
if max(c[1:])<0:
    print(max(c[1:]))
    sys.exit()

    
used=[0 for i in range(n+1)]
#1からn+1までの辺で試す
ans=-float("INF")
for i in range(1,n+1):
  #すでに探索したループは見なくて良い
  if used[i]==1:
    continue
  #今自分が居ることろをnow
  #一周のループの合計 loop_sum
  now=i
  loop=[i]
  loop_sum=0
  #連結部分を見つける
  while(1):
      loop.append(p[now])
      loop_sum+=c[p[now]]
      now=p[now]
      used[now]=1
      if p[now]==i:
          loop_sum+=c[p[now]]
          break
  #この連結なループの中で最大値を求める
  length=len(loop)
  #aから始まってk回移動
  for a in loop:
      #一周する前での最大値
      max_cost=-float("INF")
      cnt=0
      cost=0
      while cnt<length:
          cnt+=1
          a=p[a]
          cost+=c[a]
          if max_cost<cost:
            max_cost=cost
            max_num=cnt
          if cnt==k:
              ans=max(ans,max_cost)
              break
      
      if loop_sum<0:
        ans=max(ans,max_cost)
      else:
        ans=max(ans,max_cost+((k-max_num)//length)*loop_sum)
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()))
loop = []
visit = [False for i in range(n)]
for i in range(n):
    if visit[i]:
        continue
    tyu  = [i]
    now = i
    visit[i] = True
    while True:
        nex = p[now] - 1
        if nex == i:
            break
        visit[nex] = True
        tyu.append(nex)
        now = nex
    loop.append(tyu)

ans = []

for p in loop:
    kouho = []
    losum = 0
    lokz = len(p)
    kar = [0]
    for i in p:
        losum += c[i]
        kar.append(kar[-1] + c[i])
    if losum > 0:
        kouho.append(losum*(k//lokz))
        for i in range(1,lokz+1):
            for j in range(1,lokz+1):
                if i < j:
                    amari = j - i
                    if amari <= k:
                        cou = losum*((k-amari)//lokz) + kar[j-1]-kar[i-1]
                elif i == j:
                    continue
                elif i > j:
                    amari = lokz - (i-j)
                    if amari <= k:
                        cou = losum*((k-amari)//lokz) + kar[j-1] + kar[-1] - kar[i-1]
                kouho.append(cou)
    elif losum <= 0:
        for i in range(lokz):
            for j in range(lokz):
                if i <= j:
                    amari = j - i
                    if amari <= k:
                        cou = kar[j-1]-kar[i-1]
                elif i > j:
                    amari = lokz - (i-j)
                    if amari <= k:
                        cou = kar[j-1] + kar[-1] - kar[i-1]
                kouho.append(cou)
    ans.append(max(kouho))
print(max(ans))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque
from collections import Counter
import math

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

n,k = readInts()
p = [0]+readInts()
c = [0]+readInts()

ans = -1*float("inf")
for i in range(1,n+1):
	j = p[i]
	t = [0]
	al = set()
	while j not in al:
		t.append(t[-1]+c[j])
		al.add(j)
		j = p[j]
	if t[-1]<0:
		ans = max(ans, max(t[1:k+1]))
	else:
		kuri = k//(len(t)-1)
		s = kuri*t[-1]
		ans = max(ans, max(s,s+max(t[:k-kuri*(len(t)-1)+1])))

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque
from collections import Counter
import math

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

n,k = readInts()
p = [0]+readInts()
c = [0]+readInts()

past = [False]*(n+1)
ans = -1-float("inf")
for i in range(1,n+1):
	j = p[i]
	if past[j]: continue
	past[j] = True
	t = [0]
	al = set()
	while j not in al:
		t.append(t[-1]+c[j])
		al.add(j)
		j = p[j]
	if t[-1]<0:
		ans = max(ans, max(t[1:k+1]))
	else:
		kuri = k//(len(t)-1)
		s = kuri*t[-1]
		ans = max(ans, max(s,s+max(t[:k-kuri*(len(t)-1)+1])))

print(ans)

Submission status: Wrong Answer

Solution code:
n, k = (int(x) for x in input().split())
P = list(int(x) - 1 for x in input().split())
C = list(int(x) for x in input().split())

ans = -1e18
for si in range(n):
    A = [C[si]]
    total = C[si]
    x = P[si]
    while x != si:
        A.append(C[x])
        total += C[x]
        x = P[x]
    m = len(A)
    tmp = 0
    for i in range(min(m, k)):
        tmp += A[i]
        if total > 0:
            ans = max(ans, tmp + total * (k-i-1)//m)
        else:
            ans = max(ans, tmp)
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()))

cycle = [[0,0] for _ in range(N)]

for start in range(N):
    now, score, moves = start, 0, 0
    while True:
        now = P[now] - 1
        score += C[now]
        moves += 1

        if now == start: break
    
    cycle[start] = [moves, score]

ans = -10**18
for start in range(N):
    cycle_moves, cycle_score = cycle[start]
    if cycle_score < 0 or K < cycle_moves:
        now = P[start]-1
        score = C[now]
        moves_left = min(K,cycle_moves)-1
    else:
        now = start
        score = (K // cycle_moves) * cycle_score
        moves_left = K % cycle_moves
    
    max_score = score
    while moves_left > 0:
        now = P[now] - 1
        score += C[now]
        max_score = max(max_score,score)

        moves_left -= 1
    
    ans = max(ans,max_score)

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque
from collections import Counter
import math

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

n,k = readInts()
p = [0]
p.extend(readInts())
c = [0]
c.extend(readInts())

past = [False]*(n+1)
ans = -100000000
for i in range(1,n+1):
	j = p[i]
	if past[j]: continue
	past[j] = True
	t = [0]
	al = []
	while j not in al:
		t.append(t[-1]+c[j])
		al.append(j)
		j = p[j]
	if t[-1]<0:
		ans = max(ans, max(t[1:k+1]))
	else:
		kuri = k//(len(t)-1)
		s = kuri*t[-1]
		ans = max(ans, max(s,s+max(t[:k-kuri*(len(t)-1)+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()))

cycle = [[0,0] for _ in range(N)]

for start in range(N):
    now, score, moves = start, 0, 0
    while True:
        now = P[now] - 1
        score += C[now]
        moves += 1

        if now == start: break
    
    cycle[start] = [moves, score]

ans = -10**18
for start in range(N):
    cycle_moves, cycle_score = cycle[start]
    if cycle_score < 0:
        now = P[start]-1
        score = C[now]
        moves_left = cycle_moves-1
    else:
        if K >= cycle_moves:
            now = start
            score = (K // cycle_moves) * cycle_score
            moves_left = K % cycle_moves
        else:
            now = P[start]-1
            score = C[now]
            moves_left = K-1

    max_score = score
    while moves_left > 0:
        now = P[now] - 1
        score += C[now]
        max_score = max(max_score,score)

        moves_left -= 1
    
    ans = max(ans,max_score)

print(ans)

Submission status: Wrong Answer

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

def sim(start,mx): # simulate mx step from start, returns max_score
    if mx==0:
        return 0
    now_p=0
    nxt=p[start]-1
    cnt=0
    p_lis=[]

    while True:
        nxt=p[nxt]-1
        now_p+=c[nxt]
        p_lis.append(now_p)
        cnt+=1
        if cnt==mx:
            break

    return max(p_lis)

visited_p=set() # already checked flag
cycle_score=[] # cycle loop score
cycle_points=[]
now_cycle=0


for i in range(n):
    if i in visited_p:
        continue
    visited_p.add(i)
    now_p=0
    nxt=p[i]-1
    visited=set()
    while True:
        nxt=p[nxt]-1
        visited_p.add(nxt)
        if nxt in visited:
            break
        visited.add(nxt)
        now_p+=c[nxt]
    cycle_score.append(now_p)
    cycle_points.append(list(visited))

ans=-float('inf')

for c_num in range(len(cycle_score)):
#    print(c_num,cycle_score[c_num],cycle_points[c_num])
    cycle_len=len(cycle_points[c_num])
    for start in cycle_points[c_num]:

        if cycle_score[c_num]<0: # no loop, just check min(loop_len,k)
            score = sim(start,min(cycle_len,k))
            ans=max(ans,score)

        else: # loop as many as possible
            loop_num = k // cycle_len
            nokori=k%cycle_len
            if nokori==0:
                exit()
#                nokori=min(cycle_len,k)

            score = sim(start,nokori) + loop_num*cycle_score[c_num]
            ans=max(ans,score)

print(ans)

Submission status: Wrong Answer

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

cycle = [[0,0] for _ in range(N)]

for start in range(N):
    now, score, moves = start, 0, 0
    while True:
        now = P[now] - 1
        score += C[now]
        moves += 1

        if now == start: break
    
    cycle[start] = [moves, score]

ans = -10**18
for start in range(N):
    cycle_moves, cycle_score = cycle[start]
    if cycle_score < 0:
        now = P[start]-1
        score = C[now]
        moves_left = cycle_moves-1
    else:
        now = start
        score = (K // cycle_moves) * cycle_score
        moves_left = K % cycle_moves
    
    max_score = score
    while moves_left > 0:
        now = P[now] - 1
        score += C[now]
        max_score = max(max_score,score)

        moves_left -= 1
    
    ans = max(ans,max_score)

print(ans)

Submission status: Wrong Answer

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

cycle = [[0,0] for _ in range(N)]

for start in range(N):
    now, score, moves = start, 0, 0
    while True:
        now = P[now] - 1
        score += C[now]
        moves += 1

        if now == start: break
    
    cycle[start] = [moves, score]

ans = -10**18
for start in range(N):
    cycle_moves, cycle_score = cycle[start]
    if cycle_score < 0:
        score = C[P[start]-1]
        moves_left = cycle_moves
    else:
        score = (K // cycle_moves) * cycle_score
        moves_left = K % cycle_moves
    
    max_score, now = score, start
    while moves_left > 0:
        now = P[now] - 1
        score += C[now]
        max_score = max(max_score,score)

        moves_left -= 1
    
    ans = max(ans,max_score)

print(ans)

Submission status: Wrong Answer

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

def sim(start,mx): # simulate mx step from start, returns max_score
    if mx==0:
        return 0
    now_p=0
    nxt=p[start]-1
    cnt=0
    p_lis=[]

    while True:
        nxt=p[nxt]-1
        now_p+=c[nxt]
        p_lis.append(now_p)
        cnt+=1
        if cnt==mx:
            break

    return max(p_lis)

visited_p=set() # already checked flag
cycle_score=[] # cycle loop score
cycle_points=[]
now_cycle=0

for i in range(n):
    if i in visited_p:
        continue
    visited_p.add(i)
    now_p=0
    nxt=p[i]-1
    visited=set()
    while True:
        nxt=p[nxt]-1
        visited_p.add(nxt)
        if nxt in visited:
            break
        visited.add(nxt)
        now_p+=c[nxt]
    cycle_score.append(now_p)
    cycle_points.append(list(visited))

ans=-float('inf')

for c_num in range(len(cycle_score)):
#    print(c_num,cycle_score[c_num],cycle_points[c_num])
    cycle_len=len(cycle_points[c_num])
    for start in cycle_points[c_num]:

        if cycle_score[c_num]<0: # no loop, just check min(loop_len,k)
            score = sim(start,min(cycle_len+5,k))
            ans=max(ans,score)

        else: # loop as many as possible
            loop_num = k // cycle_len
            nokori=k%cycle_len
            if nokori==0:
                nokori=cycle_len+5

            score = sim(start,nokori) + loop_num*cycle_score[c_num]
            ans=max(ans,score)

print(ans)