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:
import sys


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        if k > le:
            tmp_1 = - float('Inf')
            div, mod = divmod(k, le)
            for i in range(le):
                tmp_3 = 0
                for j in range(le):
                    p = (i + j) % le
                    tmp_3 += s[p]
                    tmp_1 = max(tmp_1, tmp_3)

            tmp_2 = div * sum(s)
            tmp_5 = - float('Inf')
            for i in range(le):
                tmp_4 = 0
                for j in range(mod):
                    p = (i + j) % le
                    tmp_4 += s[p]
                    tmp_5 = max(tmp_5, tmp_4)
            tmp_2 += tmp_5
            tmp = max(tmp_1, tmp_2)

        else:
            for i in range(le):
                tmp_1 = 0
                for j in range(k):
                    p = (i + j) % le
                    tmp_1 += s[p]
                    tmp = max(tmp, tmp_1)

        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

js = [None for _ in range(n)] # 周期とスコア増分

for s in range(n):
    if js[s]:
        continue
    m = s
    tmp = 0
    memo = [[] for _ in range(n)]
    i = 0
    while True:
        m = p[m] - 1
        tmp += c[m]
        memo[m].append((i, tmp))
        if len(memo[m]) > 1:
            js[m] = (memo[m][1][0] - memo[m][0][0], memo[m][1][1] - memo[m][0][1])
        if len(memo[m]) > 2:
            break
        i += 1

ans = -10000000000
for s in range(n):
    m = s
    tmp = 0
    visited = [0] * n
    for i in range(k):
        m = p[m] - 1
        if visited[m]:
            break
        visited[m] = 1
        tmp += c[m]
        if js[m] and js[m][1] > 0:
            ans = max(ans, tmp + js[m][1] * (k - i - 1) // js[m][0])
        else:
            ans = max(ans, tmp)
print(ans)

Submission status: Wrong Answer

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

import copy
p_list = [[0 for _ in range(n)] for _ in range(n)]
position = [[-1 for _ in range(n)] for _ in range(n)]
shuki = [-1 for _ in range(n)]
tmp = copy.deepcopy(c)
for i in range(n):
    p_list[0][i] += c[p[i]]
    position[0][i] = p[i]    
for i in range(1, n):
    for j in range(n):
        position[i][j] = p[position[i - 1][j]]
        p_list[i][j] = p_list[i - 1][j] + c[position[i][j]]        
        if shuki[j] == -1:
            tmp[j] = max(tmp[j], p_list[i][j])
        if (position[i][j] == j) & (shuki[j] == -1):
            shuki[j] = i + 1
ans = max(c)
for i in range(n):
    v = 0
    if shuki[i] >= 0:
        if p_list[shuki[i] - 1][i] > 0:
            v += p_list[shuki[i] - 1][i] * (k // shuki[i])
            if k - (k // shuki[i]) * shuki[i] > 0:
                v += tmp[i]
        else:
            v += tmp[i]
    else:
        v += tmp[i]
    ans = max(v, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        if k > le:
            tmp_1 = - float('Inf')
            div, mod = divmod(k, le)
            for i in range(le):
                tmp_3 = 0
                for j in range(le):
                    p = i + j
                    if p >= le:
                        p -= le
                    tmp_3 += s[p]
                    tmp_1 = max(tmp_1, tmp_3)

            tmp_2 = div * sum(s)
            tmp_5 = - float('Inf')
            for i in range(le):
                tmp_4 = 0
                for j in range(mod):
                    p = i + j
                    if p >= le:
                        p -= le
                    tmp_4 += s[p]
                    tmp_5 = max(tmp_5, tmp_4)
            tmp_2 += tmp_5
            tmp = max(tmp_1, tmp_2)

        else:
            for i in range(le):
                tmp_1 = 0
                for j in range(k):
                    p = i + j
                    if p >= le:
                        p -= le
                    tmp_1 += s[p]
                    tmp = max(tmp, tmp_1)

        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
(n,k),p,c=[[*map(int,t.split())]for t in open(0)]
a=-9e9
for i in range(n):
 s=t=f=m=0;x,*l=i,
 while~f:x=p[x]-1;l+=c[x],;s+=c[x];m+=1;f-=x==i
 for j in range(min(m,k)):t+=l[j];a=max(a,t+(~j+k)//m*s)
print(a)

Submission status: Wrong Answer

Solution code:
(n,k),p,c=[[*map(int,t.split())]for t in open(0)]
a=-1e9
for i in range(n):
 s=t=f=m=0;x,*l=i,
 while~f:x=p[x]-1;l+=c[x],;s+=c[x];m+=1;f-=x==i
 for j in range(min(m,k)):t+=l[j];a=max(a,t+(~j+k)//m*s*(s>0))
print(a)

Submission status: Wrong Answer

Solution code:
(n,k),p,c=[[*map(int,t.split())]for t in open(0)]
a=-1e9
for i in range(n):
 s=t=f=m=0;x,*l=i,
 while~f:x=p[x]-1;l+=c[x],;s+=c[x];m+=1;f-=x==i
 for j in range(min(m,k)):t+=l[j];a=max(a,t+(~j+k)//m*s)
print(a)

Submission status: Wrong Answer

Solution code:
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

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

uf = UnionFind(n)

for i in range(n):
    uf.union(i,p[i])
import collections
dic = collections.defaultdict(int)
for i in uf.roots():
    dic[i] = 0
ans = 0
total = collections.defaultdict(int)
for i in range(n):
    if dic[uf.find(i)] == 0:
        ls = uf.members(i)
        for j in ls:
            total[uf.find(i)] += c[j]
        dic[uf.find(i)] = 1
ans = - (10 ** 15)
for i in range(n):
    tmp = 0
    tmp_max = - (10 ** 15)
    members_len = len(uf.members(i))
    parent = uf.find(i)
    k_tmp = k
    if total[parent] >= 0:
        if k_tmp > members_len:
            tmp += total[parent] * (k_tmp // members_len)
            k_tmp -= members_len * (k_tmp // members_len)
        tmp_max = max(tmp_max,tmp)
        while k_tmp > 0:
            tmp += c[p[i]]
            i = p[i]
            tmp_max = max(tmp_max,tmp)
            k_tmp -= 1
    else:
        k_tmp = min(members_len,k)
        while k_tmp > 0:
            tmp += c[p[i]]
            i = p[i]
            tmp_max = max(tmp_max,tmp)
            k_tmp -= 1
    ans = max(tmp_max,ans)
print(ans)

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()]
if max(score) <= 0:
  print(max(score))
else:
  pos = [0] + pos
  score = [0] + score
  max_point = -10 ** 12
  #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 = pos[f_pos]
        point_loop += score[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 point_loop > 0:
      point = loop_c * point_loop
      if point > max_point and loop_c > 0:
        max_point = point
    else:
      point = 0
      if loop_c > 0:
        r = loop
    #print(point)
    if r > 0:
      for _ in range(r):
        point += score[f_pos]
        f_pos = pos[f_pos]
        #print(point)
        if point > max_point:
          max_point = point
  #print('max_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()))

maxcost = 0
for pi in p:    # O(n^2)
    passed, curr, costs = set(), pi, [0]
    while curr not in passed:
        passed.add(curr)
        curr = p[curr-1]
        costs.append(costs[-1]+c[curr-1])
    l = len(costs) - 1
    if costs[-1] > 0:
        maxcost = max(maxcost, costs[-1]*(k//l)+max(costs[:k % l+2]))
    else:
        maxcost = max(maxcost, max(costs[:k % l+2]))

print(maxcost or max(c))

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
p = list(int(x)-1 for x in input().split())
c = list(map(int, input().split()))
score = -10**9
loop = [[] for _ in range(n+1)]
group = [0]*n
while 0 in group:
  i = group.index(0)
  here = i
  while group[i]==0:
    here = p[here]
    loop[i+1].append(here+1)
    group[here] = i+1
while [] in loop:
  loop.remove([])
#print(loop)
#print(group)
for i in loop:
  s = [0]
  cc = []
  x = -10**9-1
  for j in i:
    s.append(s[-1]+c[j-1])
    cc.append(c[j-1])
  s.remove(0)
  x = max(cc)
  ind = cc.index(x)
  cc = cc[ind+1:]+cc[:ind]
  if s[-1]>0 and len(s)<k:
    sc = x+s[-1]*(k//len(s))+sum(cc[:k%len(s)-1])
  else:
    sc = max(max(s),x)
  score = max(sc,score)
print(score)

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(mi())


def main():
    n, k = mi()
    p = list(map(lambda x: int(x)-1, input().split()))
    c = li()
    table = [[0] for _ in range(n)]
    num = set()
    for i in range(n):
        cur = i
        for j in range(n):
            cur = p[cur]
            table[i].append(table[i][-1]+c[cur])
            if cur == i:
                break
    ans = -10**18
    for i in range(n):
        tmp = 0
        d = len(table[i])-1
        r = k
        if r >= d and table[i][-1] > 0:
            tmp = r//d*table[i][-1]
            r %= d
        if r > 0:
            tmp += max(table[i][1:r+2])
        ans = max(ans, tmp)
    print(ans)
            



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(mi())


def main():
    n, k = mi()
    p = list(map(lambda x: int(x)-1, input().split()))
    c = li()
    table = [[0] for _ in range(n)]
    num = set()
    for i in range(n):
        cur = i
        for j in range(n):
            cur = p[cur]
            table[i].append(table[i][-1]+c[cur])
            if cur == i:
                break
    ans = -10**18
    for i in range(n):
        tmp = 0
        d = len(table[i])-1
        if k >= d and table[i][-1] > 0:
            tmp = k//d*table[i][-1]
            k -= k//d
        tmp += max(table[i][1:k+1])
        ans = max(ans, tmp)
    print(ans)
            



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(mi())


def main():
    n, k = mi()
    p = list(map(lambda x: int(x)-1, input().split()))
    c = li()
    table = [[0] for _ in range(n)]
    num = set()
    for i in range(n):
        cur = i
        for j in range(n):
            cur = p[cur]
            table[i].append(table[i][-1]+c[cur])
            if cur == i:
                break
    ans = 0
    for i in range(n):
        tmp = 0
        d = len(table[i])-1
        if k >= d and table[i][-1] > 0:
            tmp = k//d*table[i][-1]
            k -= k//d
        tmp += max(table[i][:k+1])
        ans = max(ans, tmp)
    print(ans)
            



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

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

uf = UnionFind(n)

for i in range(n):
    uf.union(i,p[i])
import collections
dic = collections.defaultdict(int)
for i in uf.roots():
    dic[i] = 0
ans = 0
total = collections.defaultdict(int)
for i in range(n):
    if dic[uf.find(i)] == 0:
        ls = uf.members(i)
        for j in ls:
            total[uf.find(i)] += c[j]
        dic[uf.find(i)] = 1
ans = - (10 ** 15)
for i in range(n):
    tmp = 0
    tmp_max = - (10 ** 15)
    members_len = len(uf.members(i))
    parent = uf.find(i)
    k_tmp = k
    #iからスタート
    if total[parent] >= 0:
        if k_tmp > members_len:
            tmp += total[parent] * (k_tmp // members_len)
            k_tmp -= members_len * (k_tmp // members_len)
        tmp_max = max(tmp_max,tmp)
        while k_tmp > 0:
            tmp += c[p[i]]
            i = p[i]
            tmp_max = max(tmp_max,tmp)
            k_tmp -= 1
    else:
        k_tmp = members_len
        while k_tmp > 0:
            tmp += c[p[i]]
            i = p[i]
            tmp_max = max(tmp_max,tmp)
            k_tmp -= 1
    ans = max(tmp_max,ans)
print(ans)

Submission status: Wrong Answer

Solution code:
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

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

uf = UnionFind(n)

for i in range(n):
    uf.union(i,p[i])
import collections
dic = collections.defaultdict(int)
for i in uf.roots():
    dic[i] = 0
ans = 0
total = collections.defaultdict(int)
for i in range(n):
    if dic[uf.find(i)] == 0:
        ls = uf.members(i)
        for j in ls:
            total[uf.find(i)] += c[j]
        dic[uf.find(i)] = 1
ans = - (10 ** 15)
for i in range(n):
    tmp = 0
    tmp_max = - (10 ** 15)
    members_len = len(uf.members(i))
    parent = uf.find(i)
    k_tmp = k
    #iからスタート
    if total[parent] >= 0:
        if k_tmp > members_len:
            tmp += total[parent] * (k_tmp // members_len)
            k_tmp -= members_len * (k_tmp // members_len)
        tmp_max = max(tmp_max,tmp)
        while k_tmp > 0:
            tmp += c[p[i]]
            i = p[i]
            tmp_max = max(tmp_max,tmp)
            k_tmp -= 1
    else:
        k_tmp = members_len
        tmp_max = max(tmp_max,tmp)
        while k_tmp > 0:
            tmp += c[p[i]]
            i = p[i]
            tmp_max = max(tmp_max,tmp)
            k_tmp -= 1
    ans = max(tmp_max,ans)
print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split()) # 2 ≤ N ≤ 5000  ; 1 ≤ K ≤ 10^9
P = list(map(int,input().split()))
C = list(map(int,input().split())) # −10^9 ≤ C[i] ≤ 10^9

ring_P = []

def get_score(PP):
    max_score = K * -10**9
    #score = [0] * K
    score_sum = sum([C[i-1] for i in PP])
    KK = K%len(PP) if K%len(PP) != 0 else 3
    for j in range(KK):
        score_0 = 0
        for h in range(j+1):
            score_0 += C[PP[(h) % len(PP)]-1]
#        score[j] = score_sum
        max_score = max(max_score, score_0)
        for i in range(1,len(PP)):
            #score_0 = score[j]
            ind_1  = PP[(i+j) % len(PP)]
            ind_0  = PP[(i-1) % len(PP)]
            score_1p = C[PP[(i+j) % len(PP)]-1]
            score_1m = C[PP[(i-1) % len(PP)]-1]
            score_1 = score_0 + (C[PP[(i+j) % len(PP)]-1] - C[PP[(i-1) % len(PP)]-1])
            #score[j] = max(score_0, score_1)
            max_score = max(max_score, score_1)
            score_0 = score_1
    if score_sum > 0:
        max_score += score_sum * ((K -KK) // len(PP))
    return max_score

max_score = K * -10**9
Arr = [0] * (N+1)
i = 1
while i < N+1:
    if Arr[i] != 1:
        #ring_P.append([])
        #PP = ring_P[-1]
        PP = []
        Arr[i] = 1
        init = i
        i = P[i-1]
        #print(i)
        PP.append(i)
        while init != i:
            Arr[i] = 1
            i = P[i-1]
            #print(i)
            PP.append(i)
        #print(PP)
        #print([C[i-1] for i in PP])
        #print(get_score(PP))
        max_score = max(get_score(PP),max_score)
    i += 1
#print(ring_P)
print(max_score)

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()]
if max(score) <= 0:
  print(max(score))
else:
  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_loop = 0
      loop = 0
      pos_set = set([f_pos])
      while True:
        f_pos = pos[f_pos]
        point_loop += score[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 point_loop > 0:
      point = loop_c * point_loop
      if point > max_point and loop_c > 0:
        max_point = point
    else:
      point = 0
      if loop_c > 0:
        r = loop
    #print(point)
    if r > 0:
      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,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     
def main():
    N, K = LI()
    P = LI_()
    C = LI()
    G = [-1 for _ in range(N)]
    for i, p in enumerate(P):
        G[i] = p
    seen = set()

    loop_score = []
    loop_size = []
    loop_id2node = collections.defaultdict(list)

    _id = 0
    def calc_one_loop(v):
        nodes = set()
        if G[v] == -1:
            return -1, -1
        # calc loop, and return score
        score = 0
        size = 0
        while G[v] not in seen:
            v = G[v]
            seen.add(v)
            nodes.add(v)
            score += C[v]
            size += 1
        return score, size, nodes

    for i in range(N):
        if i in seen:
            continue
        score, size, nodes = calc_one_loop(i)
        if score == -1 and size == -1:
            continue
        loop_score.append(score)
        loop_size.append(size)
        loop_id2node[_id].extend(list(nodes))
        seen.add(i)
        _id += 1

    ans = -inf
    for i in range(_id):
        # i: id
        n_loop = K // loop_size[i]

        # score_afterを作る
        score_after = [[0] for _ in range(N)]
        for v in loop_id2node[i]:
            max_move_cnt = loop_size[i] + 1
            move_cnt = 0
            cum_score = 0
            cur_v = v
            while move_cnt < max_move_cnt:
                cur_v = G[cur_v]
                cum_score += C[cur_v]
                score_after[v].append(cum_score)
                move_cnt += 1
        # print('score_after: ', score_after)
        # amari = min(K, loop_size[i])
        if loop_score[i] <= 0:
            max_step = min(K, loop_size[i])
            score = 0
        else:
            # 先に回る
            # ちょうど1周だったら、回らない
            if K == loop_size[i]:
                max_step = K
                score = 0
            else:
                K -= max(n_loop, 0) * loop_size[i]
                max_step = K
                score = max(n_loop, 0) * loop_score[i]

        # loop_size[i]より小さい数で全探索
        oneloop_max = -inf
        for l in range(1, max_step + 1):
            for v in loop_id2node[i]:
                cp_score = score
                cnt = 0
                cp_score += score_after[v][l]
                oneloop_max = max(oneloop_max, cp_score)
        ans = max(ans, oneloop_max)
    print(ans)

main()

Submission status: Wrong Answer

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

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


ans = -INF
for i in range(N):
    nx = i
    total = 0
    L = [] 
    while True:
        nx = P[nx]
        total += C[nx]
        L.append(C[nx])
        if nx == i:
            break
    now = 0
    l = len(L)
    for j in range(l):
        if j + 1 > K:
            break
        now += L[j]
        ans = max(ans, now)
    if total <= 0:
        continue
    if K < l:
        continue
    now = (K // l) * total
    ans = max(ans, now)
    r = K % l
    for j in range(r):
        now += L[j]
        ans = max(ans, now)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

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


ans = -INF
for i in range(N):
    nx = i
    total = 0
    l = [] 
    while True:
        nx = P[nx]
        total += C[nx]
        l.append(C[nx])
        if nx == i:
            break
    now = 0
    for e in l:
        now += e
        ans = max(ans, now)
    if total <= 0:
        continue
    if K < len(l):
        continue
    now = (K // len(l)) * total
    ans = max(ans, now)
    r = K % len(l)
    for j in range(r):
        now += l[j]
        ans = max(ans, now)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

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


ans = -INF
for i in range(N):
    nx = i
    total = 0
    l = [] 
    while True:
        nx = P[nx]
        total += C[nx]
        l.append(C[nx])
        if nx == i:
            break
    now = 0
    for e in l:
        now += e
        ans = max(ans, now)
    if total <= 0:
        continue
    now = (K // len(l)) * total
    ans = max(ans, now)
    r = K % len(l)
    for j in range(r):
        now += l[j]
        ans = max(ans, now)
print(ans)