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=[int(x)-1 for x in input().split()]
C=[int(x) for x in input().split()]

def circle_grouping(P):
  P_in=[]
  P_group=[]
  for i in range(N):
    if i in P_in:
      pass
    else:
      start=i
      j=P[i]
      ls=[i]
      P_in.append(i)
      while j!=start:
        ls.append(j)
        P_in.append(j)
        j=P[j]
      P_group.append(ls)
  return P_group

def circle_maximum(A,K):
  max_val=max(A)
  for i in range(len(A)):
    val=0
    for k in range(K):
      pos=(i+k)%len(A)
      val+=A[pos]
      max_val=max(max_val,val)
  return max_val

score=max(C)
P_group=circle_grouping(P)
for A in P_group:
  k_rem=K%len(A)
  cycle=K//len(A)
  if k_rem==0:
    k_rem=len(A)
    cycle-=1
    
  B=[C[i] for i in A]
  if sum(B)>0:
    score=max(score,sum(B)*cycle+circle_maximum(B,k_rem))
  else:
    score=max(score,circle_maximum(B,k_rem))
print(score)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007



class UnionFind:
    def __init__(self, n):
        # 負  : 根であることを示す。絶対値はランクを示す
        # 非負: 根でないことを示す。値は親を示す
        self.table = [-1] * n
        self.size = [1] * n
        # self.group_num = n

    def root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.root(self.table[x])
            return self.table[x]

    def get_size(self, x):
        r = self.root(x)
        return self.size[r]

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

    def union(self, x, y):
        r1 = self.root(x)
        r2 = self.root(y)
        if r1 == r2:
            return
        # ランクの取得
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.size[r1] += self.size[r2]
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2
            self.size[r2] += self.size[r1]
        # self.group_num -= 1

n, k = LI()
P = LI()
C = LI()
U = UnionFind(n)
for i in range(n):
    U.union(P[i] - 1, i)

D = defaultdict(int)
for i in range(n):
    D[U.root(i)] += C[i]

ans = -INF
for j in range(n):
    r = D[U.root(j)]
    m = U.get_size(j)
    ret = 0
    now = j
    if k // m and r >= 0:
        ret_max = 0
        for l in range(k % m):
            now = P[now] - 1
            ret += C[now]
            ret_max = max(ret_max, ret)
        ret_max += k // m * r
    else:
        ret_max = -INF
        for l in range(min(m, k)):
            now = P[now] - 1
            ret += C[now]
            ret_max = max(ret_max, ret)
    ans = max(ans, ret_max)

print(ans)

Submission status: Wrong Answer

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

def circle_grouping(P):
  P_in=[]
  P_group=[]
  for i in range(N):
    if i in P_in:
      pass
    else:
      start=i
      j=P[i]
      ls=[i]
      P_in.append(i)
      while j!=start:
        ls.append(j)
        P_in.append(j)
        j=P[j]
      P_group.append(ls)
  return P_group

def circle_maximum(A,K):
  if K==0:
    return 0
  else:
    max_val=max(A)
    for i in range(len(A)):
      val=0
      for k in range(K-1):
        pos=(i+k)%len(A)
        val+=A[pos]
        max_val=max(max_val,val)
    return max_val

score=max(C)
P_group=circle_grouping(P)
for A in P_group:
  k_rem=K%len(A)
  B=[C[i] for i in A]
  if sum(B)>0:
    score=max(score,sum(B)*(K//len(B))+circle_maximum(B,k_rem))
  else:
    score=max(score,circle_maximum(B,k_rem))
print(score)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007



class UnionFind:
    def __init__(self, n):
        # 負  : 根であることを示す。絶対値はランクを示す
        # 非負: 根でないことを示す。値は親を示す
        self.table = [-1] * n
        self.size = [1] * n
        # self.group_num = n

    def root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.root(self.table[x])
            return self.table[x]

    def get_size(self, x):
        r = self.root(x)
        return self.size[r]

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

    def union(self, x, y):
        r1 = self.root(x)
        r2 = self.root(y)
        if r1 == r2:
            return
        # ランクの取得
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.size[r1] += self.size[r2]
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2
            self.size[r2] += self.size[r1]
        # self.group_num -= 1

n, k = LI()
P = LI()
C = LI()
U = UnionFind(n)
for i in range(n):
    U.union(P[i] - 1, i)

D = defaultdict(int)
for i in range(n):
    D[U.root(i)] += C[i]

ans = -INF
for j in range(n):
    r = D[U.root(j)]
    m = U.get_size(j)
    ret = 0
    now = j
    if k // m and r >= 0:
        ret_max = 0
        for l in range(k % m):
            now = P[now] - 1
            ret += C[now]
            ret_max = max(ret_max, ret)
        ret_max += k // m * r
    else:
        ret_max = -INF
        for l in range(k):
            now = P[now] - 1
            ret += C[now]
            ret_max = max(ret_max, ret)
    ans = max(ans, ret_max)

print(ans)

Submission status: Wrong Answer

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

def circle_grouping(P):
  P_in=[]
  P_group=[]
  for i in range(N):
    if i in P_in:
      pass
    else:
      start=i
      j=P[i]
      ls=[i]
      P_in.append(i)
      while j!=start:
        ls.append(j)
        P_in.append(j)
        j=P[j]
      P_group.append(ls)
  return P_group

def circle_maximum(A,K):
  if K==0:
    return 0
  else:
    max_val=max(A)
    for i in range(len(A)):
      val=0
      for k in range(K-1):
        pos=(i+k)%len(A)
        val+=A[pos]
        max_val=max(max_val,val)
    return max_val

score=max(C)
P_group=circle_grouping(P)
for A in P_group:
  k_rem=K%len(A)
  print(k_rem)
  B=[C[i] for i in A]
  if sum(B)>0:
    score=max(score,sum(B)*(K//len(B))+circle_maximum(B,k_rem))
  else:
    score=max(score,circle_maximum(B,k_rem))
print(score)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007



class UnionFind:
    def __init__(self, n):
        # 負  : 根であることを示す。絶対値はランクを示す
        # 非負: 根でないことを示す。値は親を示す
        self.table = [-1] * n
        self.size = [1] * n
        # self.group_num = n

    def root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.root(self.table[x])
            return self.table[x]

    def get_size(self, x):
        r = self.root(x)
        return self.size[r]

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

    def union(self, x, y):
        r1 = self.root(x)
        r2 = self.root(y)
        if r1 == r2:
            return
        # ランクの取得
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.size[r1] += self.size[r2]
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2
            self.size[r2] += self.size[r1]
        # self.group_num -= 1

n, k = LI()
P = LI()
C = LI()
U = UnionFind(n)
for i in range(n):
    U.union(P[i] - 1, i)

D = defaultdict(int)
for i in range(n):
    D[U.root(i)] += C[i]

ans = -INF
for j in range(n):
    r = D[U.root(j)]
    m = U.get_size(j)
    ret_max = 0 if k // m and r >= 0 else -INF
    ret = 0
    now = j
    t = k % m if r > 0 else min(k, m)
    for l in range(t):
        now = P[now] - 1
        ret += C[now]
        ret_max = max(ret_max, ret)
    if r > 0:
        ret_max += r * (k // m)
    ans = max(ans, ret_max)

print(ans)

Submission status: Wrong Answer

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

def circle_grouping(P):
  P_in=[]
  P_group=[]
  for i in range(N):
    if i in P_in:
      pass
    else:
      start=i
      j=P[i]
      ls=[i]
      P_in.append(i)
      while j!=start:
        ls.append(j)
        P_in.append(j)
        j=P[j]
      P_group.append(ls)
  return P_group

def circle_maximum(A,K):
  max_val=max(A)
  for i in range(len(A)):
    val=0
    for k in range(K):
      pos=(i+k)%len(A)
      val+=A[pos]
      max_val=max(max_val,val)
  return max_val

score=max(C)
P_group=circle_grouping(P)
for A in P_group:
  k_rem=K%len(A)
  B=[C[i] for i in A]
  if sum(B)>0:
    score=max(score,sum(B)*(K//len(B))+circle_maximum(B,k_rem))
  else:
    score=max(score,circle_maximum(B,k_rem))
print(score)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007



class UnionFind:
    def __init__(self, n):
        # 負  : 根であることを示す。絶対値はランクを示す
        # 非負: 根でないことを示す。値は親を示す
        self.table = [-1] * n
        self.size = [1] * n
        # self.group_num = n

    def root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.root(self.table[x])
            return self.table[x]

    def get_size(self, x):
        r = self.root(x)
        return self.size[r]

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

    def union(self, x, y):
        r1 = self.root(x)
        r2 = self.root(y)
        if r1 == r2:
            return
        # ランクの取得
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.size[r1] += self.size[r2]
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2
            self.size[r2] += self.size[r1]
        # self.group_num -= 1

n, k = LI()
P = LI()
C = LI()
U = UnionFind(n)
for i in range(n):
    U.union(P[i] - 1, i)

D = defaultdict(int)
for i in range(n):
    D[U.root(i)] += C[i]

ans = -INF
for j in range(n):
    r = D[U.root(j)]
    m = U.get_size(j)
    ret_max = 0
    ret = 0
    now = j
    t = k % m if r > 0 else min(k, m)
    for l in range(t):
        now = P[now] - 1
        ret += C[now]
        ret_max = max(ret_max, ret)
    if r > 0:
        ret_max += r * (k // m)
    ans = max(ans, ret_max)

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

max = -10000000000

for i in range(1,N+1):
    naw = i
    S = 0
    l = 0
    lmax = -10000000000
    kl = K

    while 1:
        naw = p[naw]
        S += c[naw]
        l += 1
        kl -= 17
        if S > lmax:
            lmax = S
            max_l = l
        if kl == 0 or naw == i:
            break
    
    if kl == 0:
        imax = lmax
    else:
        if S <= 0:
            imax = lmax
        else:
            imax = lmax + S * ( (K - max_l) // l)
    
    if (imax > max):
        max = imax

print(max)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
pos = [int(i) for i in input().split()]
score = [int(i) for i in input().split()]
pos = [0] + pos
score = [0] + score
max_point = -10 ** 12
dic = {}
for i in range(1, n + 1):
  f_pos = i
  #print('f_pos',f_pos)
  if f_pos not in dic:
    point = 0
    loop = 0
    count = 0
    pos_set = set([f_pos])
    while True:
      f_pos = pos[f_pos]
      point += score[f_pos]
      #print('pos', f_pos)
      #print(point)
      count += 1
      if f_pos in pos_set:
        loop = count
        for j in pos_set:
          dic[j] = [loop, point]
        break
      pos_set.add(f_pos)
  else:
    loop = dic[f_pos][0]
    point = dic[f_pos][1]
  #print(loop, point)
  loop_c = k // loop
  r = k % loop
  if point > 0:
    point *= loop_c
    if point > max_point and loop_c > 0:
      max_point = point
  else:
    point = 0
    if loop_c > 0:
      r = loop
  #print(point)
  for _ in range(r):
    f_pos = pos[f_pos]
    point += score[f_pos]
    #print(point)
    if point > max_point:
      max_point = point
#print('max_point')
print(max_point)

Submission status: Wrong Answer

Solution code:
import math
n,k = map(int,input().split())
plist= list(map(int,input().split()))
plist = [p-1 for p in plist]
clist= list(map(int,input().split()))

n_max = [[] for _ in range(n)]

used = set()
used_node = [[] for _ in range(n)]
for i in range(n):
    start = plist[i]
    if start in used:
        continue
    first = start
    for j in range(n):
        if j != 0 and start == first:
            break
        used.add(start)
        used_node[i].append(start)
        n_max[i].append(clist[start])
        start = plist[start]

max_score = -math.inf
for i in range(n):
    i_score = n_max[i]
    if i_score == []:
        continue

    score = 0
    node_max = -math.inf
    if k < n:
        remain = k
    else:
        remain = n
    if sum(i_score) > 0:
        score = (k//len(i_score))*sum(i_score)
        remain = k-(k//len(i_score)*len(i_score))

    i_score = i_score * 2
    temp_max = -math.inf
    temp_score = 0

    for j in range(remain+1):
        for k in range(remain+1):
            temp_score = sum(i_score[j:j+k])
            temp_max = max(temp_score,temp_max)
    score += temp_max
    max_score = max(score,max_score)

print(max_score)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
s = [[0] for _ in range(n)]
ans = -10**18
 
for i in range(n):
    flag = 0
    a = p[i]
    s[i].append(c[a-1])
    while flag == 0:
        a = p[a-1]
        if a == i + 1:
            flag = 1
        s[i].append(c[a-1]+ s[i][-1])
 
for i in range(n):
    a = 0
    mul = k//(len(s[i])-1)
    m = mul*(s[i][-1] > 0)
    re = k - m*(len(s[i])-1)
 
    a += m*s[i][-1]
    if len(s[i][1:min(re+1, len(s[i])-1)]):
        a += max(s[i][1:min(re+1, len(s[i])-1)])
    
    f = s[i].index(max(s[i][1:-1]))
    al = s[i][-1]*min(0, m-1) + s[i][f]
    if al > a and m>0:
        a = al
    
    if a > ans:
        ans = a
print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
P = [i-1 for i in P]
ans = -1e18
for si in range(N):
    x = si
    s = []
    tot = 0
    while True:
        x = P[x]
        s.append(C[x])
        tot += C[x]
        if x == si :
            break
    l = len(s)
    t = 0
    for i in range(l):
        t += s[i]
        if i+1 > K:
            break
        now = t
        if tot > 0:
            e = (K-i-1)/l
            now += tot*e
        if ans < now:
            ans = now
        else:
            ans = ans
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
def main():
    import sys

    sys.setrecursionlimit(10 ** 4)

    def search_loop(now: int, loop: list):
        """iから探索を初めて，再びiに達するまでに通った点のスコアをリストとして返す"""
        seen[now] = True
        if now == i and loop:
            loops.append(loop)
            return
        loop.append(C[now])
        search_loop(P[now], loop)

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

    # ループを探す
    seen = [False] * N
    loops = []
    for i in range(N):
        if not seen[i]:
            search_loop(i, [])

    # ループごとの最大スコアを探す
    ans = -10 ** 9
    for i in range(N):
        now = i
        loop = []
        while now != i or not loop:
            loop.append(C[now])
            now = P[now]
        length = len(loop)
        sum_loop = sum(loop)
        # ループ長よりも操作回数が多いか？，ループを周回すると得か？で場合分け
        res = 0 if sum_loop <= 0 else sum_loop * (K // length)
        limit = K if K <= length else K % length

        # loop_temp = loop * 2  # loopリストに同じloopリストを接続する
        for k in range(limit):
            res += loop[k]
            ans = max(ans, res)
    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()))
s = [[0] for _ in range(n)]
ans = -10**18
 
for i in range(n):
    flag = 0
    a = p[i]
    s[i].append(c[a-1])
    while flag == 0:
        a = p[a-1]
        if a == i + 1:
            flag = 1
        s[i].append(c[a-1]+ s[i][-1])
 
for i in range(n):
    a = 0
    mul = k//(len(s[i])-1)
    m = mul*(s[i][-1] > 0)
    re = k - m*(len(s[i])-1)
 
    a += m*s[i][-1]
    if len(s[i][1:min(re+1, len(s[i])-1)]):
        a += max(s[i][1:min(re+1, len(s[i])-1)])
    
    f = s[i].index(max(s[i][1:-1]))
    al = mul*min(0, m-1) + s[i][f]
    if al > a and m>0:
        a = al
    
    if a > ans:
        ans = a
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()))
s = [[0] for _ in range(n)]
ans = -10**18
 
for i in range(n):
    flag = 0
    a = p[i]
    s[i].append(c[a-1])
    while flag == 0:
        a = p[a-1]
        if a == i + 1:
            flag = 1
        s[i].append(c[a-1]+ s[i][-1])
 
for i in range(n):
    a = 0
    mul = k//(len(s[i])-1)
    m = mul*(s[i][-1] > 0)
    re = k - m*(len(s[i])-1)
 
    a += m*s[i][-1]
    if len(s[i][1-(m!=0):min(re+1, len(s[i])-1)]):
        a += max(s[i][1-(m!=0):min(re+1, len(s[i])-1)])
    
    f = s[i].index(max(s[i][1:-1]))
    al = mul*max(0, m-1) + s[i][f]
    if al > a and m>0:
        a = al
    
    if a > ans:
        ans = a
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()))
s = [[0] for _ in range(n)]
ans = -10**18

for i in range(n):
    flag = 0
    a = p[i]
    s[i].append(c[a-1])
    while flag == 0:
        a = p[a-1]
        if a == i + 1:
            flag = 1
        s[i].append(c[a-1]+ s[i][-1])

for i in range(n):
    a = 0
    mul = k//(len(s[i])-1)
    m = mul*(s[i][-1] > 0)
    re = k - m*(len(s[i])-1)

    a += m*s[i][-1]
    if len(s[i][1-(m!=0):min(re+1, len(s[i])-1)]):
        a += max(s[i][1-(m!=0):min(re+1, len(s[i])-1)])
    
    f = s[i].index(max(s[i][1:-1]))
    al = mul*min(0, m-1) + s[i][f]
    if al > a and m>0:
        a = al
    
    if a > ans:
        ans = a
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()))
s = [[0] for _ in range(n)]
ans = -10**18

for i in range(n):
    flag = 0
    a = p[i]
    s[i].append(c[a-1])
    while flag == 0:
        a = p[a-1]
        if a == i + 1:
            flag = 1
        s[i].append(c[a-1]+ s[i][-1])

for i in range(n):
    a = 0
    mul = k//(len(s[i])-1)
    m = mul*(s[i][-1] > 0)
    re = k - m*(len(s[i])-1)

    a += m*s[i][-1]
    if len(s[i][1-(m!=0):min(re+1, len(s[i])-1)]):
        a += max(s[i][1-(m!=0):min(re+1, len(s[i])-1)])
    
    f = s[i].index(max(s[i][1:-1]))
    al = mul*min(0, m-1) + s[i][f]
    if al > a:
        a = al
    
    if a > ans:
        ans = a
print(ans)

Submission status: Wrong Answer

Solution code:
from numba import jit
@jit
def main():
    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    ans = -float('inf')
    
    for i in range(n):
        start, count = i, 1
        val = c[start]
        while p[start]-1 != i:
            start = p[start]-1
            count += 1
            val += c[start]

        start = i
        if val > 0:
            a = (k//count-1)*val
            ans = max(a, ans)
            num = k%count+count
        else:
            a = 0
            num = min(k, count)

        for _ in range(num):
            start = p[start]-1
            a += c[start]
            ans = max(a, ans)
    print(int(ans))

main()

Submission status: Wrong Answer

Solution code:
from numba import jit
@jit
def main():
    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    ans = -float('inf')
    
    for i in range(n):
        start, count = i, 1
        val = c[start]
        while p[start]-1 != i:
            start = p[start]-1
            count += 1
            val += c[start]

        start = i
        if val > 0:
            a = (k//count-1)*val
            if a > ans:
                ans = a
            num = k%count+count
        else:
            a = 0
            num = min(k, count)

        for _ in range(num):
            start = p[start]-1
            a += c[start]
            if a > ans:
                ans = a
    print(int(ans))

main()

Submission status: Wrong Answer

Solution code:
import math
n,k = map(int,input().split())
plist= list(map(int,input().split()))
clist= list(map(int,input().split()))

n_max = [[] for _ in range(n)]

used = set()
used_node = [[] for _ in range(n)]
for i in range(n):
    start = plist[i]-1
    if start in used:
        continue
    score = 0
    first = start
    for j in range(n):
        if j != 0 and start == first:
            break
        score += clist[start]
        used.add(start)
        used_node[i].append(start)
        start = plist[start]-1
        n_max[i].append(score)

max_score = -math.inf
for i in range(n):
    i_score = n_max[i]
    if i_score == []:
        continue

    for node in used_node[i]:

        score = 0
        node_max = -math.inf
        used = used_node[i].index(node)
        if k < n:
            remain = k
        else:
            remain = n
        if i_score[-1] > 0:
            score = (k//len(i_score))*i_score[-1]

            remain = k-(k//len(i_score)*len(i_score))

        start = plist[node]-1
        temp_max = -math.inf
        temp_score = 0

        for j in range(remain):
            temp_score += clist[start]
            start = plist[start]-1
            temp_max = max(temp_score,temp_max)
        score += temp_max
        max_score = max(score,max_score)

print(max_score)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
def main():
    import sys

    sys.setrecursionlimit(10 ** 4)

    def search_loop(now: int, loop: list):
        """iから探索を初めて，再びiに達するまでに通った点のスコアをリストとして返す"""
        seen[now] = True
        if now == i and loop:
            loops.append(loop)
            return
        loop.append(C[now])
        search_loop(P[now], loop)

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

    # ループを探す
    seen = [False] * N
    loops = []
    for i in range(N):
        if not seen[i]:
            search_loop(i, [])

    # ループごとの最大スコアを探す
    ans = -10 ** 9
    for loop in loops:
        length = len(loop)
        sum_loop = sum(loop)
        # ループ長よりも操作回数が多いか？，ループを周回すると得か？で場合分け
        res = 0 if sum_loop <= 0 else sum_loop * (K // length)
        limit = K if K <= length else K % length

        loop_temp = loop * 2  # loopリストに同じloopリストを接続する
        for i in range(length):
            cal = res
            for k in range(limit):
                cal += loop_temp[i + k]
                ans = max(ans, cal)
    print(ans)


if __name__ == '__main__':
    main()