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
input = sys.stdin.readline

n, k = map(int, input().split())
parr = list(map(int, input().split()))
carr = list(map(int, input().split()))
scores = []

for i in range(n):
  cur = i
  # 1ループで通るノードの数とスコア
  roop_num = 0
  roop_score = 0
  while True:
    cur = parr[cur] - 1
    roop_num += 1
    roop_score += carr[cur]
    if cur == i:
      break
  tmp_max = -10**9
  # ループしたときにスコアが減るとき
  # kが1ループの回数より小さいとき
  if roop_score <= 0:
    score = 0
    max_iter = roop_num
  elif k < roop_num:
    score = 0
    max_iter = k
  else:
    # ループする回数
    num = k // roop_num
    score = roop_score*num
    max_iter = k - roop_num*num
  cur = i
  for _ in range(max_iter):
      cur = parr[cur] - 1
      score += carr[cur]
      if score > tmp_max:
        tmp_max = score
  scores += [tmp_max]

print(max(scores))

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
input = sys.stdin.readline


def print_ans(N, K, pr, cr):
    """Test Case
    >>> print_ans(5, 3,[2, 4, 5, 1, 3], [3, 4, -10, -8, 8])
    8
    >>> print_ans(2, 3,[2, 1],[10, -7])
    13
    """
    ans = 0

    maximum = 0
    pr = np.array(pr)
    pr = pr - 1
    cr = np.array(cr)
    maximum = max(maximum, np.max(cr))
    ar = cr.copy()
    for i in range(K):
        if len(ar.shape) == 1:
            newest = ar.copy()
        else:
            newest = ar[i, :].copy()
        tmp = newest[pr]
        ar = np.vstack((ar, tmp))
        tmp_sum = np.sum(ar, axis=0)
        maximum = max(maximum, np.max(tmp_sum))
    print(maximum)


if __name__ == '__main__':
    N, K = map(int, input().rstrip().split())
    pr = list(map(int, input().rstrip().split()))
    cr = list(map(int, input().rstrip().split()))
    print_ans(N, K, pr, cr)

Submission status: Wrong Answer

Solution code:
def max2(x,y):
    return x if x > y else y

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

off = max(C)
m2 = off
for i in range(N):
    tmp = 0
    m1 = off
    l = i
    S = 0
    k = 0
    for j in range(N):
        S += C[l]
        l = P[l] - 1
        if l==i:
            k = j+1
            break
    cnt = K // k - (K % k == 0)
    a = K-cnt*k + (K % k == 0)*k
    l = i
    for j in range(a):
        tmp += C[l]
        m1 = max2(m1, tmp)
        l = P[l] - 1
    if S > 0:
        m1 += cnt*S
    m2 = max2(m1, m2)

print(m2)
"""
4 10
2 3 4 1
1 2 3 4
"""

Submission status: Wrong Answer

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

F=[0]*N
I=[0]*N
CN=[0]*N
if max(C)<0:
  print(max(C))
  exit()

for i in range(N):
  around=0
  cnt=0
  A=[]
  if F[i]==0:
    F[i]=1
    around+=1
    cnt+=C[i]
    nex=P[i]-1
    A.append(i)
    while F[nex]==0:
      A.append(nex)
      F[nex]=1
      around+=1
      cnt+=C[nex]
      nex=P[nex]-1
    for j in A:
      I[j]=around
      CN[j]=cnt
#print(F)
#print(I)
#print(CN)
ans=-(10**9)*2
for i in range(N):
  cnt=C[i]
  #動かす回数が一周に満たない時
  if (K+1)<=I[i]:
    d=0
    nex=i
    for j in range(K+1):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
  #動かす回数が一周を超えるとき
  elif CN[i]<0:
    d=0
    nex=i
    for j in range(I[i]):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
  else:
    d=0
    nex=i
    for j in range(I[i]):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
    acnt=cnt
    bcnt=C[i]
    print(i,acnt)
    syuukai=(K+1)//I[i]
    nokori=(K+1)%I[i]
    syuukai-=1
    nokori+=I[i]
    d=0
    nex=i
    for j in range(nokori):
      d+=C[nex]
      nex=P[nex]-1
      bcnt=max(d,bcnt)
      if i==1:
        print(d)
    bcnt+=syuukai*CN[i]
    cnt=max(acnt,bcnt)
  ans=max(ans,cnt)
print(ans)

Submission status: Wrong Answer

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

reach = [False]*n
x = []
for i in range(n):
    if reach[i]:continue
    buf = []
    index = i
    while not reach[index]:
        buf.append(c[index])
        reach[index] = True
        index = p[index]
    x.append(buf)

ans = max(c)
import itertools
for i in x:
    n = k//len(i)
    ind = k%len(i)
    ii = i+i+i
    r = list(itertools.accumulate(ii))
    a = r[len(i)-1]*n
    for j in range(len(i)):
        for z in range(1,min(len(i)*2,k)+1):
            s = r[j+z]-r[j]
            if z<ind+1:
                ans = max(ans,a+s)
            ans = max(ans,s)
print(ans)

Submission status: Wrong Answer

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

n, k = map(int, input().split())
parr = list(map(int, input().split()))
carr = list(map(int, input().split()))
scores = []

for i in range(n):
  cur = i
  # 1ループで通るノードの数とスコア
  roop_num = 0
  roop_score = 0
  while True:
    cur = parr[cur] - 1
    roop_num += 1
    roop_score += carr[cur]
    if cur == i:
      break
  tmp_max = -10**9
  # ループしたときにスコアが減るとき
  # kが1ループの回数より小さいとき
  if roop_score <= 0:
    score = 0
    max_iter = roop_num
  elif k < roop_num:
    score = 0
    max_iter = k
  else:
    # ループする回数
    n = k // roop_num
    score = roop_score*n
    max_iter = k - roop_num*n
  cur = i
  for _ in range(max_iter):
      cur = parr[cur] - 1
      score += carr[cur]
      if score > tmp_max:
        tmp_max = score
  scores += [tmp_max]

print(max(scores))

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 = -10000000

if K <= N:
    for i in range(N):
        count = 0
        tmp_point = 0
        nv = i
        while count < K:
            nvv = P[nv]
            nvv -= 1
            tmp_point += C[nvv]
            count += 1
            nv = nvv
            ans = max(ans, tmp_point)
    print(ans)
else:
    loop = [0]*N
    for i in range(N):
        count = 0
        check = [False]*N
        tmp_point = 0
        nv = i
        while True:
            nvv = P[nv]
            nvv -= 1
            if check[nvv] == True:
                break
            check[nvv] = True
            tmp_point += C[nvv]
            count += 1
            nv = nvv
            ans = max(ans, tmp_point)
        loop[i] = [tmp_point, count, i]
    loop.sort(reverse=True)
    #print(loop)
    new_ans = -10000000
    for value, counter, key in loop:
        if value < 0:
            break
        shou = K//counter
        amari = K%counter
        tmp_ans = value*shou    
        new_ans = max(new_ans, tmp_ans)
        count = 0
        nv = key
        while count < amari:
            nvv = P[nv]
            nvv -= 1
            tmp_ans += C[nvv]
            count += 1
            nv = nvv
            new_ans = max(new_ans, tmp_ans)

        shou = K//counter
        amari = K%counter
        if amari == 0:
            amari = counter
            shou -= 1
            tmp_ans = value*shou    
            new_ans = max(new_ans, tmp_ans)
            count = 0
            nv = key
            while count < amari:
                nvv = P[nv]
                nvv -= 1
                tmp_ans += C[nvv]
                count += 1
                nv = nvv
                new_ans = max(new_ans, tmp_ans)

    print(max(loop[0][0], ans, new_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()))
mx=-float("inf")


for i in range(n):

  sc=0
  pn=i
  mass=[0]*n
  for j in range(k):
    pn=p[pn]-1
        
    if mass[pn]!=0:
      lpk=j-mass[pn][0]
      amari=(k-j)%lpk
      lpsc=sc-mass[pn][1]
      #print(sc)
      for l in range(amari):
        sc+=c[pn]
        pn=p[pn]-1
        mx=max(mx,sc)
      sc+=lpsc*((k-j-amari)//lpk)
      mx=max(mx,sc)
      #print(lpk,j,amari,lpsc)
      break
    
    mass[pn]=[j,sc]
    sc+=c[pn]
    mx=max(mx,sc)
  #print(mass)
print(mx)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
mx=-float("inf")


for i in range(n):

  sc=0
  pn=i
  mass=[0]*n
  for j in range(k):
    pn=p[pn]-1
        
    if mass[pn]!=0:
      lpk=j-mass[pn][0]
      amari=(k-j)%lpk
      lpsc=sc-mass[pn][1]
      print(sc)
      for l in range(amari):
        sc+=c[pn]
        pn=p[pn]-1
        mx=max(mx,sc)
      sc+=lpsc*((k-j-amari)//lpk)
      mx=max(mx,sc)
      #print(lpk,j,amari,lpsc)
      break
    
    mass[pn]=[j,sc]
    sc+=c[pn]
    mx=max(mx,sc)
  #print(mass)
print(mx)

Submission status: Wrong Answer

Solution code:
import sys
import math
import collections
import bisect
import itertools

# import numpy as np

sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip().split())
na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))


# ===CODE===

# https://note.nkmk.me/python-union-find/

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

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


def main():
    n, k = ns()
    p = na1()
    c = na()

    uf = UnionFind(n)
    for i, pi in enumerate(p):
        uf.union(i, pi)

    cycledist = [[-INF for _ in range(2)] for __ in range(n)]
    for lis in uf.all_group_members().values():
        if cycledist[lis[0]][0] != -INF:
            continue
        tmp = 0
        l = len(lis)
        for idx in lis:
            tmp += c[idx]
            cycledist[idx][1] = l

        for idx in lis:
            cycledist[idx][0] = tmp

    ans = -INF

    for i in range(n):
        tmp_ans = cycledist[i][0] * (k // cycledist[i][1])

        tmp = 0
        idx = i
        for _ in range(min(k, cycledist[i][1])):
            tmp += c[p[idx]]
            idx = p[idx]
            if _ < k % cycledist[i][1]:
                ans = max(ans, tmp, tmp + tmp_ans)
            else:
                ans = max(ans, tmp)

    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()))
ans = -float("inf")
for i in range(N):
    hoge = []
    p = i
    s = 0
    for j in range(K):
        p = P[p]-1
        s += C[p]
        hoge.append(s)
        ans = max(ans,s)
        if p == i:
            s = max(s*((K-1)//len(hoge)) + max(hoge[:(K-1)%len(hoge)+1]),s*((K-1)//len(hoge)-1) + max(hoge) )
            ans = max(ans,s)
            break
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 = -10000000

if K <= N:
    for i in range(N):
        count = 0
        tmp_point = 0
        nv = i
        while count < K:
            nvv = P[nv]
            nvv -= 1
            tmp_point += C[nvv]
            count += 1
            nv = nvv
            ans = max(ans, tmp_point)
    print(ans)
else:
    loop = [0]*N
    for i in range(N):
        count = 0
        check = [False]*N
        tmp_point = 0
        nv = i
        while True:
            nvv = P[nv]
            nvv -= 1
            if check[nvv] == True:
                break
            check[nvv] = True
            tmp_point += C[nvv]
            count += 1
            nv = nvv
            ans = max(ans, tmp_point)
        loop[i] = [tmp_point, count, i]
    loop.sort(reverse=True)
    #print(loop)
    new_ans = -10000000
    for value, counter, key in loop:
        if value < 0:
            break
        shou = K//counter
        amari = K%counter
        tmp_ans = value*shou    
        new_ans = max(new_ans, tmp_ans)
        count = 0
        nv = key
        while count < amari:
            nvv = P[nv]
            nvv -= 1
            tmp_ans += C[nvv]
            count += 1
            nv = nvv
            new_ans = max(new_ans, tmp_ans)

        if amari == 0:
            amari = counter
            shou -= 1
            tmp_ans = value*shou    
            new_ans = max(new_ans, tmp_ans)
            count = 0
            nv = key
            while count < amari:
                nvv = P[nv]
                nvv -= 1
                tmp_ans += C[nvv]
                count += 1
                nv = nvv
                new_ans = max(new_ans, tmp_ans)

    print(max(loop[0][0], ans, new_ans))

Submission status: Wrong Answer

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

n, k = map(int, input().split())
parr = list(map(int, input().split()))
carr = list(map(int, input().split()))
scores = []

for i in range(n):
  cur = i
  # 1ループで通るノードの数とスコア
  roop_num = 0
  roop_score = 0
  while True:
    cur = parr[cur] - 1
    roop_num += 1
    roop_score += carr[cur]
    if cur == i:
      break
  tmp_max = -10**9
  # ループしたときにスコアが減るとき
  # kが1ループの回数より小さいとき
  if roop_score <= 0:
    score = 0
    max_iter = roop_num
  elif k < roop_num:
    score = 0
    max_iter = k
  else:
    # ループする回数
    n = k // roop_num
    score = roop_score*n
    max_iter = k - roop_num*n
  for _ in range(max_iter):
      cur = parr[cur] - 1
      score += carr[cur]
      if score > tmp_max:
        tmp_max = score
  scores += [tmp_max]

print(max(scores))

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()))
was = [False]*n
sums = []
for i in range(n):
    if not was[i]:
        iWas = [False]*n
        pos = i
        sumn = [c[i]]
        while not iWas[pos]:
            iWas[pos] = True
            was[pos] = True
            pos = p[pos]-1
            sumn+=[c[pos]]
        sumn = sumn[:-1]
        sums.append(sumn)
m = -9999999999999999999999999
for i in range(len(sums)):
    totS = sum(sums[i])
    l = len(sums[i])
    for g in range(len(sums[i])):
        arr = []
        s = 0
        for j in range(l):
            s+=sums[i][(g+j)%l]
            arr.append(s)

        if totS > 1:
            add = max(arr[:k%l+1]+[-99999999999999999999])
            if add != -99999999999999999999:
                if k//l:
                    m = max(m,totS*(k//l)+max(add,0))
                else:
                    m = max(m,add)
            else:
                m = max(m,totS*(k//l))

        else:

            m = max(m, max(arr[:min(l,k)+1]))
print(m)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**9)
N, K = map(int, input().split())
P = list(map(lambda x:int(x)-1, input().split()))
C = list(map(int, input().split()))
weight = []
visited = [0]*N
ans = - float('inf')

def dfs(u, cnt, w):
  w += [C[u]]
  visited[u] = 1
  v = P[u]
  if visited[v] != 1:
    dfs(v, cnt+1, w)
  else:
    return


for i in range(N):
  weight = []
  visited = [0]*N
  dfs(i, 1, weight)

  if len(weight) > K:
    weight = weight[:K]
    tmp = 0
    for j in range(K-1):
      weight[j+1] += weight[j]
    tmp = max(weight)
    ans = max(ans, tmp)
  else:
    s = sum(weight)
    if s > 0:
      tmp = (K//len(weight))*s
      weight = weight[:K%len(weight)]
      if len(weight) > 1:
        for j in range(len(weight)-1):
          weight[j+1] += weight[j]
        if max(weight) > 0:
          tmp += max(weight)
      elif len(weight) == 1:
        if weight[0] > 0:
          tmp += weight[0]
      ans = max(ans, tmp)
    else:
      tmp = 0
      for j in range(len(weight)-1):
        weight[j+1] += weight[j]
      tmp = max(weight)
      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()))
m = C[0]
for i in range(N):
  p = i
  s = 0
  j = 0
  while j < K:
    if p == i and j >= 1:
      if s <= 0:
        break
      else:
        s = s * int(K/j)
        j = j + (int(K/j) - 1) * j
    p = P[p]-1
    s = s + C[p]
    if s > m:
      m = s
    j = j + 1
print(m)

Submission status: Wrong Answer

Solution code:

def max2(x,y):
    return x if x > y else y

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

off = max(C)
m2 = off
for i in range(N):
    tmp = 0
    m1 = off
    l = i
    S = []
    S3 = 0
    k = 0
    visited = [-1]*N
    for r in range(N):
        S.append(C[l])
        S3 += C[l]
        m2 = max2(m2, S3)
        visited[l] = r
        l = P[l] - 1
        if visited[l] != -1:
            k = r - visited[l] + 1
            break
    r += 2
    S1 = sum(S[r - k:])
    S2 = sum(S[:r - k])
    cnt = (K - (r - k)) // k - (K % k == 0)
    a = K - k*cnt - (r-k) + (K % k == 0)*k
    for j in range(a):
        tmp += C[l]
        m1 = max2(m1, tmp)
        l = P[l] - 1
    if S1 > 0:
        m1 += cnt*S1 + S2
    m2 = max2(m1, m2)

print(m2)
"""
4 10
2 1 4 3
1 2 3 -1
"""

Submission status: Wrong Answer

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

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

# 各点からスタートして、
# (1)得点の累計
# (2)ループするまでの各点までの最高点
# (3)ループするのに必要な回数
# (4)ループしきったときの得点変化
# を記録
# 得点変化が正のときは、できるだけループした上で、残り回数を使って(2)より最高点を求める

ans = -(10 ** 10)
for i in range(N): # スタート
  now = i
  point_sum = 0
  best = []
  cnt = 0
  while True:
    cnt += 1
    point_sum += C[now]
    if len(best) == 0:
      best.append(point_sum)
    else:
      best.append(max(best[-1], point_sum))
    now = P[now]
    if now == i:
      break
  point = 0
  if point_sum > 0:
    point += point_sum * (K // cnt)
  rest = K % cnt
  point += best[rest - 1]
  
  if K // cnt > 0: # 最後のループを回りきらないほうが良い場合を考慮
    if best[-1] > point_sum: # 最後のループを回りきるよりも、ループの途中のほうが得点が高い場合
      if point_sum > 0:
        if point < best[-1] + point_sum * (K // cnt - 1):
          point = best[-1] + point_sum * (K // cnt - 1)
      else:
        if point < best[-1]:
          point = best[-1]
  
  if ans < point:
    ans = point
  #print("i",i,"ans",ans)

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()))
was = [False]*n
sums = []
for i in range(n):
    if not was[i]:
        iWas = [False]*n
        pos = i
        sumn = [c[i]]
        while not iWas[pos]:
            iWas[pos] = True
            was[pos] = True
            pos = p[pos]-1
            sumn+=[c[pos]]
        sumn = sumn[:-1]
        sums.append(sumn)
m = -9999999999999999999999999
for i in range(len(sums)):
    totS = sum(sums[i])
    l = len(sums[i])
    for g in range(len(sums[i])):
        arr = []
        s = 0
        for j in range(l):
            s+=sums[i][(g+j)%l]
            arr.append(s)

        if totS > 1:
            add = max(arr[:k%l]+[-99999999999999999999])
            if add != -99999999999999999999:
                if k//l:
                    m = max(m,totS*(k//l)+max(add,0))
                else:
                    m = max(m,add)
            else:
                m = max(m,totS*(k//l))

        else:

            m = max(m, max(arr[:min(l,k)]))
print(m)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
c = [1] * N
s = [C[P[i]-1] for i in range(N)]
m = [[0] * (N+1) for i in range(N)]
for i in range(N):
    m[i][1] = (C[P[i]-1])
for i in range(N):
    j = i
    while P[j]-1 != i:
        j = P[j]-1
        c[i] += 1
        s[i] += C[P[j]-1]
        if  c[i] <= K:
            if s[i] > m[i][c[i]-1]:
                m[i][c[i]] = s[i]
            else:
                m[i][c[i]] = m[i][c[i]-1]
ans = max(C)
for i in range(N):
    if s[i] > 0:
        if  s[i] * (K//c[i]) + m[i][K%c[i]] > ans:
            ans = s[i] * (K//c[i]) + m[i][K%c[i]]
    else:
        if m[i][min(c[i],K)] > ans:
            ans = m[i][min(c[i],K)]
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 = -999999999999999
z = 0
l = 0
lv = 0

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

    #print(cl)

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

for i in range(n):
    v = 0
    tmp = i
    for j in range(k):
        if j <= k-1:
            tmp = p[tmp]-1
            v += c[tmp]
            if ans < v:
                ans = v
            #print(tmp,v,ans) 

print(ans+z)

Submission status: Wrong Answer

Solution code:
import math
import numpy as np
import collections
import bisect
from collections import deque
from copy import copy, deepcopy
 
 
def main():
    N,K = map(int,input().split())
    P = list(map(int,input().split()))
    C = list(map(int,input().split()))
    ans=-10e10
    tmp_sum_list = [None for i in range(N)]
    for p in range(1,N+1):
        _p=p
        end=False
        tmp_list=[]
        p_list=[]
        if tmp_sum_list[p-1] is None:
            for i in range(N):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_sum=sum(tmp_list)
            tmp_len=len(tmp_list)
            for _p in p_list:
                tmp_sum_list[_p-1]=(tmp_sum,tmp_len)

        if tmp_sum_list[p-1][0]<=0:
            continue
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            for i in range(tmp_sum_list[p-1][1]):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            tmp_ans=tmp_max
        else:
            tmp_ans=(K//(tmp_sum_list[p-1][1]))*tmp_sum_list[p-1][0]
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            mod = K%tmp_sum_list[p-1][1]
            for j in range(mod):
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
            continue
            tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            tmp_ans+=tmp_max

        ans = max(ans,tmp_ans)
    print(ans)
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()))

ans = max(C)
for i in range(N):
    s = i
    l = [C[i]]
    while True:
        s = P[s]
        if s == i:
            break
        l.append(C[s])
        

    if sum(l) > 0:
        c = K//len(l)*sum(l)
        n = K%len(l)
        ans = max(ans,c)
        s = i
        for j in range(n):
            c += C[s]
            s = P[s]
            ans = max(ans,c)

    n = min(N,K)
    s = i
    c = 0
    for j in range(n):
        c += C[s]
        s = P[s]
        ans = max(ans,c)
            
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()))
seen = set()
circuits = []

for x in range(N):
    cir = []
    point = 0
    while True:
        if x in seen: 
            if cir != []: circuits.append((cir,point))
            break
        seen.add(x)
        point += C[x]
        cir.append(x)
        x = P[x] - 1
ans = -1000000000000
for x in circuits:
    tmp = 0
    if x[1] > 0 and K >= len(x[0]) * 2: 
        tmp = (K // len(x[0]) - 1) * x[1]
        r = K % len(x[0]) + len(x[0])
    if x[1] < 0 and K >= len(x[0]) * 2: 
        r = K % len(x[0]) + len(x[0])
    else:
        r = K
    for y in x[0]:
        tmp2 = 0
        for _ in range(r):
            y = P[y] - 1
            tmp2 += C[y]
            ans = max(ans, tmp + tmp2)
print(ans)

Submission status: Wrong Answer

Solution code:
"""
task statement
==============

高橋君は 1, 2, \cdots, N の番号のついた N マスから成るマス目の上で、コマを使ってゲームを行おうとしています。マス i には整数 C_i が書かれています。また、1, 2 …, N の順列 P_1, P_2, \cdots, P_N が与えられています。
これから高橋君は好きなマスを 1 つ選んでコマを 1 つ置き、1 回以上 K 回以下の好きな回数だけ、次のような方法でコマを移動させます。

1 回の移動では、現在コマがマス i (1 \leq i \leq N) にあるなら、コマをマス P_i に移動させる。このとき、スコアに C_{P_i} が加算される。

高橋君のために、ゲーム終了時のスコアとしてあり得る値の最大値を求めてください。(ゲーム開始時のスコアは 0 です。)

io_style
-------
N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N
"""
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(100000)


def main():
    n, k = [int(i) for i in input().strip().split()]
    P = [None] + [int(i) for i in input().strip().split()]
    C = [None] + [int(i) for i in input().strip().split()]
    seen = set()
    loops = []
    score = []
    loop_sums = []
    loop_max = []
    ans = -float("inf")

    if max(C[1:]) < 0:
        ans = max(C[1:])
        print(ans)
        return

    # ループを探す
    for i in range(1, n + 1):
        flag = False
        loop = []
        sc = []
        _sum = 0
        j = i
        if j not in seen:
            flag = True
            while j not in loop:
                loop.append((j))
                sc.append(C[j])
                seen.add(j)
                _sum += C[j]
                j = P[j]
        if flag:
            loops.append(loop)
            loop_sums.append(_sum)
            score.append(sc)

    # 各ループで作れる最大値を出す
    _max = []
    for i in range(len(loops)):
        loop = loops[i]
        sc = score[i]
        _max = -float("inf")
        # 各始点からループを始める
        for j in range(len(loop)):
            # 1周してみる
            _tmp = 0
            for p in range(min(len(loop) - 1, k)):  # 進める歩数はループの回数とkの小さい方
                ptr = (j + p) % len(loop)
                _tmp += sc[ptr]
                _max = max(_max, _tmp)

        # そのループの最大値を記録する
        loop_max.append(_max)

    """
    print("loops", loops)
    print("score", score)
    print("loop_sums", loop_sums)
    print("loop_max", loop_max)
    """

    # 各ループについて評価する
    for i in range(len(loops)):
        loop = loops[i]
        sc = score[i]
        _sum = loop_sums[i]  # ループの合計値
        _max = loop_max[i]  # 周回せずにループで得られる最大値

        # 周回しない場合
        ans = max(ans, _max)

        # 周回する場合
        loop_sum = _sum * (k // (len(loop)))
        ans = max(ans, loop_sum)
        res = k % len(loop)

        # 各始点からループを始める
        if res > 0:
            _res_max = -float("inf")
            for j in range(len(loop)):
                # 1周してみる
                _tmp = 0
                # 残ってるホップ回数で作れる最大値を探す
                for p in range(res):
                    ptr = (j + p) % len(loop)
                    _tmp += sc[ptr]
                    _res_max = max(_res_max, _tmp)
            ans = max(ans, loop_sum + _res_max)
    print(ans)
    return


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()))
ans=-10**10
for st in range(N):
  now = st+1
  temp=[0]
  while(P[now-1] != st+1):
    temp.append(temp[-1]+C[P[now-1]-1])
    now = P[now-1]
    temp.append(temp[-1]+C[P[now-1]-1])
  if len(temp)>=K+1:
    ans=max(ans, max(temp[1:K+1]))
    continue
  if temp[-1]<=0:
    ans = max(ans, (max(temp[1:])))
  else:
    t=temp[-1]*(K//(len(temp)-1))-temp[-1]
    t+=max(temp+[temp[-1]+temp[i+1] for i in range(K%(len(temp)-1))])
    ans=max(ans, t)
		
print(int(ans))