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 = [0] + list(map(int, input().split()))
c = [0] + list(map(int, input().split()))

freq = [0] * (n+1)
x = [0] * (n+1)
score = [[0] for _ in range(n+1)]
for i in range(1, n+1):
    check = [False] * (n+1)
    check[i] = True
    now = i
    cnt = 0
    while True:
        if check[p[now]]:
            x[i] = score[i][-1] + c[p[now]]
            score[i].append(c[p[now]] + score[i][-1])
            freq[i] = cnt + 1
            break

        now = p[now]
        check[now] = True
        score[i].append(c[now] + score[i][-1])
        cnt += 1

ans = -10**10
for i in range(1, n+1):
    if freq[i] <= k:
        if x[i] >= 0:
            tmp = k % freq[i]
            ans = max(
                ans, max(score[i][:tmp + 1]) + (k//freq[i]) * x[i]
            )
        else:
            tmp = freq[i]
            ans = max(
                ans, max(score[i][1:tmp + 1])
            )
    else:
        tmp = k
        ans = max(
            ans, max(score[i][1:tmp + 1])
        )

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

freq = [0] * (n+1)
x = [0] * (n+1)
score = [[0] for _ in range(n+1)]
for i in range(1, n+1):
    check = [False] * (n+1)
    check[i] = True
    now = i
    cnt = 0
    while True:
        if check[p[now]]:
            x[i] = score[i][-1] + c[p[now]]
            score[i].append(c[p[now]] + score[i][-1])
            freq[i] = cnt + 1
            break

        now = p[now]
        check[now] = True
        score[i].append(c[now] + score[i][-1])
        cnt += 1

ans = -10**9
for i in range(1, n+1):
    if freq[i] <= k:
        if x[i] >= 0:
            tmp = k % freq[i]
            ans = max(
                ans, max(score[i][:tmp + 1]) + (k//freq[i]) * x[i]
            )
        else:
            tmp = freq[i]
            ans = max(
                ans, max(score[i][1:tmp + 1])
            )
    else:
        tmp = k
        ans = max(
            ans, max(score[i][1:tmp + 1])
        )

print(ans)

Submission status: Wrong Answer

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

vis = [False for i in range(n)]
ans = -(10**9+1)
for i in range(n):
  tmp = 0
  if vis[i]:
    continue
  r = []
  vis[i] = True
  s = p[i]
  r.append(c[i])
  while not vis[s]:
    vis[s] = True
    r.append(c[s])
    s = p[s]
  l = len(r)
  rr = r*2
  su = sum(r)
  if k//l > 0:
    tmp = su*(k//l)
  for j in range(l):
    st = 0
    for h in range(min(l-1,k%l)):
      st = sum(rr[j:j+h+1])
      # print (st)
      ans = max(ans, st)
      ans = max(ans, st+tmp)
  # if tmp > 0:
  #   ans += tmp
print (ans)

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input=sys.stdin.readline
    n,k=map(int,input().split())
    p=list(map(int,input().split()))
    c=list(map(int,input().split()))
    
    ans=-10**12
    for i in range(n):
        visited=[0]*n
        mvnum=0
        score=0
        scorebymove=[0]
        now=p[i]-1
        while (not visited[now]) and mvnum<=k:
            mvnum+=1
            visited[now]=mvnum
            score+=c[now]
            ans=max(ans,score)
            now=p[now]-1
        mvrem=k-mvnum
        if score>=0 and mvnum<=k:
            score+=score*(mvrem//mvnum)
            mvrem-=mvnum*(mvrem//mvnum)
            ans=max(ans,score)
        else:mvrem=mvnum
        
        while mvrem>0:
            now=p[now]-1
            score+=c[now]
            ans=max(ans,score)
            mvrem-=1
            
        ans=max(ans,score)
    print(ans)
    
if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input=sys.stdin.readline
    n,k=map(int,input().split())
    p=list(map(int,input().split()))
    c=list(map(int,input().split()))
    
    ans=-10**12
    for i in range(n):
        visited=[0]*n
        mvnum=0
        score=0
        scorebymove=[0]
        now=p[i]-1
        while (not visited[now]) and mvnum<=k:
            mvnum+=1
            visited[now]=mvnum
            score+=c[now]
            scorebymove.append(score)
            ans=max(ans,score)
            now=p[now]-1
        #loopscore=score-scorebymove[visited[now]-1]
        #loopstep=mvnum-(visited[now]-1)
        mvrem=k-mvnum
        if score>=0 and mvnum<=k:
            score+=score*(mvrem//mvnum)
            mvrem-=mvnum*(mvrem//mvnum)
            ans=max(ans,score)
        else:mvrem=0
        
        while mvrem>0:
            now=p[now]-1
            score+=c[now]
            ans=max(ans,score)
            mvrem-=1
            
        ans=max(ans,score)
    print(ans)
    
if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input=sys.stdin.readline
    n,k=map(int,input().split())
    p=list(map(int,input().split()))
    c=list(map(int,input().split()))
    
    ans=-10**12
    for i in range(n):
        visited=[0]*n
        mvnum=0
        score=0
        scorebymove=[0]
        now=p[i]-1
        while (not visited[now]) and mvnum<=k:
            mvnum+=1
            visited[now]=mvnum
            score+=c[now]
            scorebymove.append(score)
            ans=max(ans,score)
            now=p[now]-1
        loopscore=score-scorebymove[visited[now]-1]
        loopstep=mvnum-(visited[now]-1)
        mvrem=k-mvnum
        if score>=0 and mvnum<=k:
            score+=loopscore*(mvrem//loopstep)
            mvrem-=loopstep*(mvrem//loopstep)
            ans=max(ans,score)
        else:mvrem=0
        
        while mvrem>0:
            now=p[now]-1
            score+=c[now]
            ans=max(ans,score)
            mvrem-=1
            
        ans=max(ans,score)
    print(ans)
    
if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input=sys.stdin.readline
    n,k=map(int,input().split())
    p=list(map(int,input().split()))
    c=list(map(int,input().split()))
    
    ans=-10**12
    for i in range(n):
        visited=[0]*n
        mvnum=0
        score=0
        scorebymove=[0]
        now=p[i]-1
        while (not visited[now]) and mvnum<=k:
            mvnum+=1
            visited[now]=mvnum
            score+=c[now]
            scorebymove.append(score)
            ans=max(ans,score)
            now=p[now]-1
        loopscore=score-scorebymove[visited[now]-1]
        loopstart=now
        loopstep=mvnum-(visited[now]-1)
        #print(visited)
        #print(scorebymove)
        #print(mvnum,visited[now])
        #print(loopscore,loopstep)
        mvrem=k-mvnum
        if score>=0 and mvnum<=k:
            score+=loopscore*(mvrem//loopstep)
            mvrem-=loopstep*(mvrem//loopstep)
            ans=max(ans,score)
        else:mvrem=0
        
        if mvrem>0:
            #print("#",mvrem,mvrem-(visited[loopstart]-1))
            score+=scorebymove[mvrem-(visited[loopstart]-1)]
        #print(score)
        ans=max(ans,score)
    print(ans)
    
if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input=sys.stdin.readline
    n,k=map(int,input().split())
    p=list(map(int,input().split()))
    c=list(map(int,input().split()))
    
    ans=-10**12
    for i in range(n):
        visited=[0]*n
        mvnum=0
        score=0
        scorebymove=[0]
        now=p[i]-1
        while (not visited[now]) and mvnum<=k:
            mvnum+=1
            visited[now]=1
            score+=c[now]
            scorebymove.append(score)
            ans=max(ans,score)
            now=p[now]-1
        mvrem=k-mvnum
        if score>=0 and mvnum<=k:
            score+=score*(mvrem//mvnum)
            ans=max(ans,score)
        else:mvrem=0
        mvrem-=mvnum*(mvrem//mvnum)
        if mvrem>0:
            score+=scorebymove[mvrem]
        ans=max(ans,score)
    print(ans)
    
if __name__=='__main__':
    main()

Submission status: Wrong Answer

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

visited=np.array([0]*n)
ans=-10**12
for i in range(n):
    mvnum=0
    score=0
    scorebymove=[0]
    now=p[i]-1
    while (not visited[now]) and mvnum<=k:
        mvnum+=1
        visited[now]=1
        score+=c[now]
        scorebymove.append(score)
        ans=max(ans,score)
        now=p[now]-1
    mvrem=k-mvnum
    if score>=0 and mvnum<=k:
        score+=score*(mvrem//mvnum)
        ans=max(ans,score)
    mvrem-=mvnum*(mvrem//mvnum)
    if mvrem>0:
        score+=scorebymove[mvrem]
    ans=max(ans,score)
    visited*=0
print(ans)

Submission status: Wrong Answer

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

visited=np.array([0]*n)
ans=-10**12
for i in range(n):
    mvnum=0
    score=0
    now=p[i]-1
    while (not visited[now]) and mvnum<=k:
        mvnum+=1
        visited[now]=1
        score+=c[now]
        ans=max(ans,score)
        now=p[now]-1
    mvrem=k-mvnum
    if score>=0 and mvnum<=k:
        score+=score*(mvrem//mvnum)
        ans=max(ans,score)
    mvrem-=mvnum*(mvrem//mvnum)
    while mvrem>0:
        score+=c[now]
        ans=max(ans,score)
        now=p[now]-1
        mvrem-=1
    ans=max(ans,score)
    visited*=0
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python3
# -*- coding:utf-8 -*-


def main():
  n, k = map(int, input().strip().split())
  lp = list(map(lambda p:int(p)-1, input().strip().split()))
  lc = list(map(int, input().strip().split()))

  used = [0] * n
  loops = []
  for i in range(n):
    if used[i] == 1:
      continue
      
    ic = i
    loop = []
    while used[ic] == 0:
      loop.append(lc[ic])
      used[ic] = 1      
      ic = lp[ic]
      
    if len(loop) > 0:
      loops.append(loop)
    
  def loop_score(loop, k):
    if sum(loop) > 0:
      score = (k // len(loop)) * sum(loop)
    return score
  
  def path_score(loop, k):
    score = 0
    for i in range(len(loop)):
      cumsum = 0
      tmp_score = 0
      for j in range(k):
        cumsum += loop[(i+j) % len(loop)]
        tmp_score = max(tmp_score, cumsum)
      score = max(tmp_score, score)
    return score
  
  def calc_score(loop, k):
    if max(loop) < 0:
      return max(loop)
    
    score = 0
    if sum(loop) > 0:
      score += loop_score(loop, k)
      k %= len(loop)
    k = min(k, len(loop)-1)
    score += path_score(loop, k)
    return score
  
  print(max([calc_score(loop, k) for loop in loops]))

if __name__=='__main__':
  main()

Submission status: Wrong Answer

Solution code:
import math

class doubling:
    def __init__(self, seni, max_jump, reward = None):
        self.depth = math.ceil(math.log2(max_jump))
        self.N = len(seni)
        self.jumps = [[0 for i in range(self.N)] for _ in range(self.depth+1)]
        self.jumps[0] = seni
        
        if reward:
            self.rewards = [[0 for i in range(self.N)] for _ in range(self.depth+1)]
            self.rewards[0] = reward
            
        for i in range(self.depth):
            for j in range(self.N):
                self.jumps[i+1][j] = self.jumps[i][self.jumps[i][j]]
                if reward:
                    self.rewards[i+1][j] = self.rewards[i][j] + self.rewards[i][self.jumps[i][j]]
    def calculation(self, now, move):
        count = move.bit_length()
        reward = 0
        for i in range(count):
            if move & 1<<i == 1<<i:
                if self.rewards:
                    reward += self.rewards[i][now]
                now = self.jumps[i][now]
        return now, reward
#%%

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

answer = -int(1e+50)
for i in range(N):
    now2, reward2 = i, 0
    for j in range(N):
        reward2 = reward2 + C[now2]
        now2 = P[now2]
        if reward2 > answer:
            answer = reward2

consume = K-N
if consume > 0:
    dbl = doubling(P, consume, C)
    for i in range(N):
        now1, reward1 = dbl.calculation(i, consume)
        for j in range(N):
            reward1 = reward1 + C[now1]
            now1 = P[now1]
            if reward1 > answer:
                answer = reward1
print(answer)

Submission status: Wrong Answer

Solution code:
import math

class doubling:
    def __init__(self, seni, max_jump, reward = None):
        self.depth = math.ceil(math.log2(max_jump))
        self.N = len(seni)
        self.jumps = [[0 for i in range(self.N)] for _ in range(self.depth+1)]
        self.jumps[0] = seni
        
        if reward:
            self.rewards = [[0 for i in range(self.N)] for _ in range(self.depth+1)]
            self.rewards[0] = reward
            
        for i in range(self.depth):
            for j in range(self.N):
                self.jumps[i+1][j] = self.jumps[i][self.jumps[i][j]]
                if reward:
                    self.rewards[i+1][j] = self.rewards[i][j] + self.rewards[i][self.jumps[i][j]]
    def calculation(self, now, move):
        count = move.bit_length()
        reward = 0
        for i in range(count):
            if move & 1<<i == 1<<i:
                if self.rewards:
                    reward += self.rewards[i][now]
                now = self.jumps[i][now]
        return now, reward
#%%

N, K = map(int, input().split())
P = list(map(lambda x: int(x)-1, input().split()))
C = list(map(int, input().split()))
#%%
consume = K-N
if consume < 1:
    consume = 1
dbl = doubling(P, consume, C)

answer = -int(1e+50)
for i in range(N):
    now1, reward1 = dbl.calculation(i, consume)
    now2, reward2 = i, 0
    for j in range(N):
        reward1 = reward1 + C[now1]
        now1 = P[now1]
        reward2 = reward2 + C[now2]
        now2 = P[now2] 
        if reward1 > answer:
            answer = reward1
            if reward1 == 53021229381:
                print(i,j)
        if reward2 > answer:
            answer = reward2
            
print(answer)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
positions = [int(i) for i in input().split()]
scores = [int(i) for i in input().split()]
if max(scores) <= 0:
  print(max(scores))
else:
  positions = [0] + positions
  scores = [0] + scores
  max_point = -pow(10, 9)
  #print(max_point)
  dic = {}
  for i in range(1, n + 1):
    f_pos = i
    #print('f_pos',f_pos)
    if f_pos not in dic:
      point_loop = 0
      loop = 0
      pos_set = set([f_pos])
      while True:
        f_pos = positions[f_pos]
        point_loop += scores[f_pos]
        #print('pos', f_pos)
        #print(point)
        loop += 1
        if f_pos in pos_set:
          for j in pos_set:
            dic[j] = [loop, point_loop]
          break
        pos_set.add(f_pos)
    else:
      loop, point_loop = dic[f_pos]
    #print(loop, point)
    loop_c = k // loop
    r = k % loop
    if loop_c ==0 or point_loop <= 0:
      if point_loop <= 0:
        r = loop
      point = 0
      for _ in range(r):
        f_pos = positions[f_pos]
        point += scores[f_pos]
        max_point = max(max_point, point)
    else:
      point1, point2 = 0, 0
      point1 = loop_c * point_loop
      max_point1 = point1
      for _ in range(r):
        f_pos = positions[f_pos]
        point1 += scores[f_pos]
        max_point1 = max(point1, max_point1)
      point2 = (loop_c - 1) * point_loop
      max_point2 = point2
      for _ in range(loop_c):
        f_pos = positions[f_pos]
        point2 += scores[f_pos]
        max_point2 = max(point2, max_point2)
      max_point = max(max_point, max(max_point1, max_point2))
  print(max_point)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
positions = [int(i) for i in input().split()]
scores = [int(i) for i in input().split()]
if max(scores) <= 0:
  print(max(scores))
else:
  positions = [0] + positions
  scores = [0] + scores
  max_point = -10 ** 9
  #print(max_point)
  for i in range(1, n + 1):
    s = []
    f_pos = positions[i]
    score = scores[f_pos]
    s.append(score)
    while f_pos != i:
      f_pos = positions[f_pos]
      score += scores[f_pos]
      s.append(score)
    loop = len(s)
    if loop > k:
      point = max(s[:k])
    else:
      loop_c = k // loop
      r = k % loop
      point1 = s[-1] * loop_c
      if r != 0:
        point1 += max(s[:r])
      point2 = s[-1] * (loop_c - 1)
      point2 += max(0, max(s))
      point = max(point1, point2)
    max_point = max(max_point, point)
  print(max_point)

Submission status: Wrong Answer

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

visit = [0]*n
r = [max(c)]

for position in range(n):
    if visit[position] > 0:
        continue

    nex = position
    pas = []

    score = [0]

    while visit[nex]<1:
        visit[nex] = 1
        pas.append(nex)
        score.append(score[-1]+c[nex])
        nex= p[nex]-1

    last = score[-1]
    count = len(score)-1

    for i in score[1:]:
        score.append(last+i)

    rou = k//count
    les = k%count

    res = [0]
    if les>0:
        for i in range(1, count+1):
            res.append(max(score[i:i+les])-score[i-1])
    r.append(rou*last + max(res))

print(max(r))

Submission status: Wrong Answer

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

visit = [0]*n
r = [max(c)]

for position in range(n):
    if visit[position] > 0:
        continue

    nex = position

    score = [0]

    while visit[nex]<1:
        visit[nex] = 1
        score.append(score[-1]+c[nex])
        nex= p[nex]-1

    last = score[-1]
    count = len(score)-1

    for i in score[1:]:
        score.append(last+i)

    rou = k//count
    les = k%count

    res = [max(score[1:count+1])]
    if les>0:
        for i in range(1, count+1):
            res.append(max(score[i:i+les])-score[i-1])
    r.append(rou*max(0, last) + max(res))


print(max(r))

Submission status: Wrong Answer

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

visit = [0]*n
r = [max(c)]

for position in range(n):
    if visit[position] > 0:
        continue

    nex = position

    score = [0]

    while visit[nex]<1:
        visit[nex] = 1
        score.append(score[-1]+c[nex])
        nex= p[nex]-1

    last = score[-1]
    count = len(score)-1

    for i in score[1:]:
        score.append(last+i)

    if (count >= k) or (last <= 0):
        result = []
        _count = min(count, k)
        for i in range(1, count+1):
            result.append(max(score[i:i+_count])-score[i-1])
        r.append(max(result))
    else:
        rou = k//count
        _count = k%count
        result = [0]
        if _count>0:
            for i in range(1, count+1):
                result.append(max(score[i:i+_count])-score[i-1])
        r.append(rou*last + max(result))

print(max(r))

Submission status: Wrong Answer

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

visit = [0]*n
r = [max(c)]

for position in range(n):
    if visit[position] > 0:
        continue

    nex = position

    score = [0]

    while visit[nex]<1:
        visit[nex] = 1
        score.append(score[-1]+c[nex])
        nex= p[nex]-1

    last = score[-1]
    count = len(score)-1

    for i in score[1:]:
        score.append(last+i)

    if (count >= k) or (last <= 0):
        result = []
        _count = min(count, k)
        for i in range(1, count+1):
            result.append(max(score[i:i+_count])-score[i-1])
        r.append(max(result))
    else:
        rou = k//count
        _count = k%count
        result = [0]
        for i in range(1, count+1):
            result.append(max(score[i:i+_count]+[0])-score[i-1])
        r.append(rou*last + max(result))

print(max(r))

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
 
ans = -10 ** 10
 
if  n >= k:
    for i in range(n):
        score = 0
        z = p[i] - 1
        for j in range(k):
            score += c[z]
            z = p[z] - 1
            ans = max(ans, score)
 
else:
    frag = []
    cyc = []
    for i in range(n):
        total = []
        tot = 0
        tol = - 10 * 10
        cyc_i = []
        z = p[i] - 1
        for j in range(n):
            tot += c[z]
            cyc_i.append(c[z])
            tol = max(tol, tot)
            total.append(tot)
            if p[i] == p[z]:
                break
            z = p[z] - 1
        frag.append(total)
        cyc.append(cyc_i)
    for i in range(n):
        if sum(cyc[i]) <= 0:
            ans = max(ans, tol)
        else:
            x = k // len(cyc[i])
            w = k % len(cyc[i])
            score = (sum(cyc[i]) * x) + frag[i][w - 1]
            ans = max(ans, score)
            for j in range(len(cyc[i])-1):
                if w >= j:
                    score -= cyc[i][w - 1 - j]
                else:
                    score -= cyc[i][len(cyc[i]) + w - j]
                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()))
 
ans = -10 * 10
for s in range(N):
    S = [] 
    i = P[s] - 1
    S.append(C[i])
    while i != s:
        i = P[i] - 1
        S.append(S[-1] + C[i])
 
    if K <= len(S):
        score = max(S[:K])
    elif S[-1] <= 0:
        score = max(S)
    else:
        score1 = S[-1] * (K // len(S) - 1)
        score1 += max(S)
        score2 = S[-1] * (K // len(S))
        r = K % len(S)
        if r != 0:
            score2 += max(0, max(S[:r]))
        score = max(score1, score2)
 
    ans = max(ans, score)
 
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

N, K = map(int, sys.stdin.readline().split())
P = list(map(int, sys.stdin.readline().split()))
C = list(map(int, sys.stdin.readline().split()))
# print(P)
# print(C)

ans = -float("inf")
for i in range(N):
    visited = set()
    loop = []
    q = deque()
    q.append((i, 0))
    # print("i", i)
    while q:
        p, c = q.popleft()
        # print(p, c)
        if p in visited:
            continue
        visited.add(p)
        loop.append(p)

        np = P[p] - 1
        q.append((np, c + C[p]))

    # print("i", i, c, len(loop))
    if c <= 0:
        tmp = 0
        tmp_ans = -float("inf")
        for j in range(min(len(loop), K+1)):
            tmp += C[loop[j]]
            tmp_ans = max(tmp_ans, tmp)
    else:
        l = K // len(loop)
        l_ans = l * c
        r = K % len(loop)
        tmp = 0
        tmp_ans = -float("inf")
        for j in range(r):
            tmp += C[loop[j]]
            tmp_ans = max(tmp_ans, tmp)
        tmp_ans += l_ans
    ans = max(ans, tmp_ans)

print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
Q = [int(i) for i in input().split()]
ans = - 10000000000
for i in range(N):
    tmp = []
    now = i
    cnt = 0
    for j in range(1, N + 1):
        now = P[now]
        cnt += Q[now]
        tmp.append(cnt)
        if now == i:
            break
    ans = max(ans, max(tmp[:K+1]))
    if tmp[j - 1] > 0:
        v = (tmp[j - 1] * (K // j))
        if K % j > 0:
            v += max(tmp[:(K % j)])
        ans = max(ans, v)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
Q = [int(i) for i in input().split()]
ans = - 10000000000
for i in range(N):
    tmp = []
    now = i
    cnt = 0
    for j in range(1, N + 1):
        now = P[now]
        cnt += Q[now]
        tmp.append(cnt)
        if now == i:
            break
    ans = max(ans, max(tmp[:K]))
    if tmp[j - 1] >= 0:
        v = (tmp[j - 1] * (K // j))
        if K % j > 0:
            v += max(tmp[:(K % j)])
        ans = max(ans, v)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
Q = [int(i) for i in input().split()]
ans = - 10000000000
for i in range(N):
    tmp = []
    now = i
    cnt = 0
    for j in range(1, N + 1):
        now = P[now]
        cnt += Q[now]
        tmp.append(cnt)
        if now == i:
            break
    ans = max(ans, max(tmp[:K]))
    if tmp[-1] >= 0:
        v = (tmp[-1] * (K // j))
        if K % j > 0:
            v += max(tmp[:(K % j)])
        ans = max(ans, v)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
Q = [int(i) for i in input().split()]
ans = - float('inf')
for i in range(N):
    now = i
    cnt = 0
    span = 0
    while True:
        span += 1
        cnt += Q[now]
        now = P[now]        
        if now == i:
            break
    point = 0
    now = i
    for j in range(1, span + 1):
        point += Q[now]
        now = P[now]       
        if j > K:
            break
        value = point + (max(cnt, 0) * (K - j) // span)
        ans = max(ans, value)
print(ans)

Submission status: Wrong Answer

Solution code:
class UnionFind():
    n=1
    par=[0]
    rnk=[0]
    def __init__(self,size):
        self.n=size
        self.par=[i for i in range(self.n)]
        self.rnk=[0 for i in range(self.n)]
    def find(self,vertex1):
        if self.par[vertex1]==vertex1:
            return vertex1
        else:
            self.par[vertex1]=self.find(self.par[vertex1])
            return self.par[vertex1]
    def unite(self,vertex1,vertex2):
        vertex1=self.find(vertex1)
        vertex2=self.find(vertex2)
        if vertex1==vertex2:
            return
        if (self.rnk[vertex1]<self.rnk[vertex2]):
            self.par[vertex1]=vertex2
        else:
            self.par[vertex2]=vertex1
            if(self.rnk[vertex1]==self.rnk[vertex2]):
                self.rnk[vertex1]+=1
    def same(self,vetrex1,vertex2):
        return self.find(vetrex1)==self.find(vertex2)

N,K=map(int,input().split())
P=[int(i)-1 for i in input().split()]
C=[int(i) for i in input().split()]
G=UnionFind(N)
for i in range(N):
    G.unite(i,P[i])
D=dict()
for i in range(N):
    if G.find(i) in D:
        D[G.find(i)]+=1
    else:
        D[G.find(i)]=1

dp=[[0 for j in range(N)] for i in range(N+1)]
for j in range(N):
    dp[0][j]=j
for i in range(N):
    for j in range(N):
        dp[i+1][j]=P[dp[i][j]]
#1 3 4 0 2
#0->1->3->0, 2->4->2
score=[[0 for j in range(N)] for i in range(N)]
for i in range(N):
    for j in range(N):
        score[i][j]=score[i-1][j]+C[dp[i+1][j]]
def maxpoint(j,L):
    if L<=N:
        return max([score[i][j] for i in range(L)])
    else:
        roop=D[G.find(j)]
        cyclepoint=score[roop-1][j]
        if cyclepoint<0:
            return maxpoint(j,roop)
        else:
            return maxpoint(j,roop)+(-1+L//roop)*cyclepoint
ans=[maxpoint(j,K) for j in range(N)]
print(max(ans))

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
Q = [int(i) for i in input().split()]
ans = - 10000000000
for i in range(N):
    tmp = []
    now = i
    cnt = 0
    for j in range(1, N + 1):
        now = P[now]
        cnt += Q[now]
        tmp.append(cnt)
        if now == i:
            break
    if tmp[-1] < 0:
        ans = max(ans, max(tmp[:K]))
    else:
        v = (tmp[-1] * (K // j))
        if K % j > 0:
            v += max(tmp[:(K % j)])
        ans = max(ans, v)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
Q = [int(i) for i in input().split()]
ans = - float('inf')
for i in range(N):
    tmp = []
    now = i
    cnt = 0
    for j in range(1, N + 1):
        now = P[now]
        cnt += Q[now]
        tmp.append(cnt)
        if now == i:
            break
    if tmp[-1] < 0:
        ans = max(ans, max(tmp[:K]))
    else:
        v = (tmp[-1] * (K // j))
        if K % j > 0:
            v += max(tmp[:(K % j)])
        ans = max(ans, v)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
Q = [int(i) for i in input().split()]
ans = - float('inf')
for i in range(N):
    tmp = []
    now = i
    cnt = 0
    for j in range(1, min(N, K) + 1):
        now = P[now]
        cnt += Q[now]
        tmp.append(cnt)
        if now == i:
            break
    if tmp[-1] < 0:
        ans = max(ans, max(tmp))
    else:
        v = (tmp[-1] * (K // j))
        if K % j > 0:
            v += max(tmp[:(K % j)])
        ans = max(ans, v)
print(ans)