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

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


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

    ans = max(C)
    for i in range(N):
        next = P[i]
        cnt = 0
        tmp = 0

        while True:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if cnt == K or next == i:
                break
            next = P[next]

        if cnt == K or tmp <= 0:
            continue

        q = K // cnt
        if q == 0:
            continue
        r = K % cnt
        next = P[i]
        tmp *= q
        ans = max(ans, tmp)
        while r > 0:
            tmp += C[next]
            ans = max(ans, tmp)
            next = P[next]
            r -= 1
    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()))

routes = []

# Pが1,2,...Nの順列なので、1,2,3,4,5,3,4,5,...のような途中からのループは起こり得ない

# どのマスから始めるか
for i in range(1, N + 1):
    # ループに入るまでの経路
    route = [i]
    visit = [False] * (N + 1)
    visit[i] = True
    now = i
    # 鳩の巣原理より、高々(N-1)回しか回らない
    while True:
        next = P[now - 1]
        # まだ訪れていないマスの場合
        if visit[next] == False:
            visit[next] = True
            route.append(next)
            now = next
        # 既に訪れたマスの場合
        else:
            break
    routes.append(route)

# print(routes)

ans = -10**9
for route in routes:
    cumsum = [0]
    for x in route:
        cumsum.append(cumsum[-1] + C[x - 1])
    # print(cumsum)
    # ループ内の何番目(1,2,...,len(route))で止まるのが一番得か
    max_value = cumsum.index(max(cumsum))
    # ループするほど損する場合
    if cumsum[-1] <= 0:
        # 1回以上操作をする必要があることに注意
        score = cumsum[1:min(K + 1, len(route))]
        ans = max(ans, max(score))
    # 出来るだけループした方が得する場合
    else:
        # ループできる回数
        loop_cnt = K // len(route)
        # 最大限ループした後に残る操作回数
        spare_K = K % len(route)
        spare_score = cumsum[1:spare_K + 2]
        max_spare_score = max(spare_score)
        # スタートの点数分は引く
        ans = max(ans, loop_cnt * cumsum[-1] +
                  max_spare_score - C[route[0] - 1])

print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
 
check = [False] * (N+10)
roop = []
 
for i in range(1, N+1):
    tmp = []
    s = P[i-1]
    while True:
        if check[s]:
            break
        check[s] = True
        tmp.append(s)
        s = P[s-1]
    if len(tmp) > 0:
        roop.append(tmp)
 
ans = -10**18
for li in roop:
    SUM = 0
    for i in li:
        SUM += C[i-1]
    length = len(li)
    try_roop = K//length
    amari = K%length
    if amari == 0:
        try_a = length
    else:
        try_a = amari
    for j in range(length):
        tmp = -10**18
        s = li[j]
        tmp1 = 0
        for k in range(try_a):
            tmp1 += C[s-1]
            now = tmp1
            if SUM > 0:
                e = (K-(k+1))//length
                now += SUM*e
            ans = max(ans, now)
            s = P[s-1]

print(ans)

Submission status: Wrong Answer

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

#到達したかの判定
#masu=[0]*(n+1)
#nは1~n
def junkan(N):
  #到達したかの判定
  masu=[0]*(n+1)
  ans=0
  ans22=-(10**9+1)
  junkan_flag=False
  now_mas=p[N-1]
  count=0
  masu[now_mas]=1
  #このwhileはせいぜい5000
  while True:
    if count!=0 and masu[now_mas]==1:
      junkan_flag=True
      break
    count+=1
    ans+=c[now_mas-1]
    
    if ans22<ans:
      ans22=ans
      
    masu[now_mas]=1
    now_mas=p[now_mas-1]
  if junkan_flag==True and ans>0:
    ans=((k-1)//count)*ans
    
    if ans22<ans:
      ans22=ans
    for i in range(k-((k-1)//count)*count):
      ans+=c[now_mas-1]
      if ans22<ans:
        ans22=ans
        
      now_mas=p[now_mas-1]
    return max(ans,ans22)
  
  else:
    return max(ans,ans22)
answ=-(10**9+1)

for i in range(1,n+1):
  hantei=junkan(i)
  if answ < hantei:
    answ=hantei
print(answ)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!

n,k=map(int,input().split())

p=list(map(lambda x:int(x)-1,input().split()))
c=list(map(int,input().split()))

lps=[]
vtd=[False]*n
for i in range(n):
    if vtd[i]:continue
    now=p[i]
    vtd[now]=True
    vc=set()
    vc.add(now)
    while now!=i:
        now=p[now]
        vtd[now]=True
        vc.add(now)
    point=0
    for v in vc:
        point+=c[v]
    lps.append((list(vc),point))

anslist=[]
for lp in lps:
    loop=lp[0]
    ls=len(loop)
    point=lp[1]
    if point<=0:
        ans=max(c)
        for first in loop:
            tmp=0
            now=first
            for j in range(min(k,ls)):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans)

        

    if point>0:
        
        ans=max(c)
        for first in loop:
            tmp=0
            now=first
            for j in range(k%ls):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans+point*((k-k%ls)//ls))
        # s=vc[100000]
print(max(anslist))

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
 
check = [False] * (N+10)
roop = []
 
for i in range(1, N+1):
    tmp = []
    s = P[i-1]
    while True:
        if check[s]:
            break
        check[s] = True
        tmp.append(s)
        s = P[s-1]
    if len(tmp) > 0:
        roop.append(tmp)
 
ans = -10**18
for li in roop:
    SUM = 0
    for i in li:
        SUM += C[i-1]
    length = len(li)
    try_roop = K//length
    amari = K%length
    if amari == 0:
        try_a = length
    else:
        try_a = amari
    for j in range(length):
        tmp = -10**18
        s = li[j]
        tmp1 = 0
        for k in range(try_a):
            tmp1 += C[s-1]
            if k+1 > K:
                break
            now = tmp1
            if SUM > 0:
                e = (K-(k+1))//length
                now += SUM*e
            ans = max(ans, now)
            s = P[s-1]

print(ans)

Submission status: Wrong Answer

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

#到達したかの判定
#masu=[0]*(n+1)
#nは1~n
def junkan(N):
  #到達したかの判定
  masu=[0]*(n+1)
  ans=0
  ans22=-(10**9+1)
  junkan_flag=False
  now_mas=p[N-1]
  count=0
  masu[now_mas]=1
  #このwhileはせいぜい5000
  while True:
    if count!=0 and masu[now_mas]==1:
      junkan_flag=True
      break
    count+=1
    ans+=c[now_mas-1]
    
    if ans22<ans:
      ans22=ans
      
    masu[now_mas]=1
    now_mas=p[now_mas-1]
  if junkan_flag==True and ans>0:
    ans=((k-1)//count)*ans
    
    if ans22<ans:
      ans22=ans
    for i in range(k%count):
      ans+=c[now_mas-1]
      if ans22<ans:
        ans22=ans
        
      now_mas=p[now_mas-1]
    return max(ans,ans22)
  
  else:
    return max(ans,ans22)
answ=-(10**9+1)

for i in range(1,n+1):
  hantei=junkan(i)
  if answ < hantei:
    answ=hantei
print(answ)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


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

    ans = max(C)
    for i in range(N):
        next = P[i]
        cnt = 0
        tmp = 0

        while True:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if cnt == K or next == i:
                break
            next = P[next]

        if cnt == K or tmp <= 0 or next != i:
            continue

        q = K // cnt
        r = K % cnt
        next = P[i]
        tmp *= q
        ans = max(ans, tmp)
        while r > 0:
            tmp += C[next]
            ans = max(ans, tmp)
            next = P[next]
            r -= 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
from collections import deque, defaultdict
def main():
    n, ko = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    scores_all = deque()
    for k1 in range(n):
        scores = deque()
        kita = defaultdict(int)
        kita[k1] = ko
        cnt = ko - 1
        koko = p[k1] - 1
        scores.append(c[koko])
        kita[koko] = cnt
        while cnt:
            cnt -= 1
            koko = p[koko] - 1
            scores.append(c[koko])
            if kita[koko]:
                break
            else:
                kita[koko] = cnt
        cycle_long = kita[koko] - cnt
        scores_a = tuple(accumulate(scores))

        if cnt:
            if scores_a[-1] > 0:
                kaisuu = ko // cycle_long
                s = scores_a[-1] * kaisuu
                amari = ko % cycle_long
                if amari:
                    t = max(0, max(scores_a[:amari]))
                    s += t
                scores_all.append(s)
            else:
                scores_all.append(max(scores_a))
        else:
            scores_all.append(max(scores_a))
    print(max(scores_all))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

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):
    ret = defaultdict(list)
    for i in range(self.n):
      ret[self.find(i)].append(i)
    return ret

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

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

uf = UnionFind(N)

for i in range(N):
  uf.union(i, P[i])

D = uf.all_group_members()
E = defaultdict(list)
F = defaultdict(int)

Num = [0]*N

for root in uf.roots():
  i = root
  n = 0
  E[root].append(0)
  while P[i] != root:
    i = P[i]
    n += 1
    Num[i] = n
    E[root].append(E[root][-1] + C[i])
  E[root].append(E[root][-1] + C[root])
  F[root] = n + 1
  #追加分
  i = root
  while P[i] != root:
    i = P[i]
    E[root].append(E[root][-1] + C[i])
  E[root].append(E[root][-1] + C[root])

#print(Num, E, F, sep="\n")
ans = -float("inf")

for root, L in E.items():
  loop, k = divmod(K, F[root])
  if k == 0:
    loop -= 1
    k += F[root]
  temp = 0
  if L[-1] >= 0:
    temp += (L[-1]//2) * loop
  for i in range(F[root]):
    for j in range(i+1, i+k+1):
      ans = max(ans, temp + E[root][j] - E[root][i])
      #print(i, j)

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

#到達したかの判定
#masu=[0]*(n+1)
#nは1~n
k-=1
def junkan(N):
  #到達したかの判定
  masu=[0]*(n+1)
  ans=0
  ans22=-(10**9+1)
  junkan_flag=False
  now_mas=p[N-1]
  count=0
  masu[now_mas]=1
  #このwhileはせいぜい5000
  while True:
    if count!=0 and masu[now_mas]==1:
      junkan_flag=True
      break
    count+=1
    ans+=c[now_mas-1]
    
    if ans22<ans:
      ans22=ans
      
    masu[now_mas]=1
    now_mas=p[now_mas-1]
  if junkan_flag==True and ans>0:
    ans=(k//count)*ans
    
    if ans22<ans:
      ans22=ans
    for i in range(k%count):
      ans+=c[now_mas-1]
      if ans22<ans:
        ans22=ans
        
      now_mas=p[now_mas-1]
    return max(ans,ans22)
  
  else:
    return max(ans,ans22)
answ=-(10**9+1)

for i in range(1,n+1):
  hantei=junkan(i)
  if answ < hantei:
    answ=hantei
print(answ)

Submission status: Wrong Answer

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

#到達したかの判定
#masu=[0]*(n+1)
#nは1~n
k-=1
def junkan(N):
  #到達したかの判定
  masu=[0]*(n+1)
  ans=0
  ans22=-(10**9+1)
  junkan_flag=False
  now_mas=p[N-1]
  count=0
  masu[now_mas]=1
  #このwhileはせいぜい5000
  while True:
    if count!=0 and masu[now_mas]==1:
      junkan_flag=True
      break
    count+=1
    ans+=c[now_mas-1]
    
    if ans22<ans:
      ans22=ans
      
    masu[now_mas]=1
    now_mas=p[now_mas-1]
  if junkan_flag==True and ans>0:
    ans=(k//count)*ans
    
    if ans22<ans:
      ans22=ans
    print(N,k,count)
    for i in range(k%count):
      ans+=c[now_mas-1]
      if ans22<ans:
        ans22=ans
        
      now_mas=p[now_mas-1]
    return max(ans,ans22)
  
  else:
    return max(ans,ans22)
answ=-(10**9+1)

for i in range(1,n+1):
  hantei=junkan(i)
  if answ < hantei:
    answ=hantei
print(answ)

Submission status: Wrong Answer

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

    def accumulate(a):
        s = 0
        yield s
        for x in a:
            s += x
            yield s

    ans = -10**9 - 1

    grp = [-1] * N
    for gid in range(N):
        if ~grp[gid]:
            continue
        cycl = []
        curr = gid
        while grp[curr] == -1:
            cycl.append(C[curr])
            grp[curr] = gid
            curr = P[curr]

        score = 0

        L = len(cycl)
        S = sum(cycl)
        if S > 0:
            score += ((K - 1) // L) * S
        K = (K - 1) % L + 1

        *acc, = accumulate(cycl)
        *acc_rev, = accumulate(reversed(cycl))

        partial = 0 if score else min(cycl)
        for right in range(L + 1):
            for rev_right in range(L + 1):
                if right == 0 and rev_right == 0 and score == 0:
                    continue
                if right + rev_right > K:
                    continue
                partial = max(partial, acc[right] + acc_rev[rev_right])

        ans = max(ans, score + partial)

        # print(f'{gid=},{grp=},{cycl=}')
        # print(f'{L=},{S=},{K=}')
        # print(f'{acc=}')
        # print(f'{acc_rev=}')
        # print(f'{score=}')
        # print(f'{partial=}')

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


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

    ans = max(C)
    for i in range(N):
        next = P[i]
        cnt = 0
        tmp = 0

        while True:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if cnt == K or next == i:
                break
            next = P[next]

        if cnt == K or tmp <= 0:
            continue

        q = K // cnt
        r = K % cnt
        next = P[i]
        tmp *= q
        ans = max(ans, tmp)
        while r > 0:
            tmp += C[next]
            ans = max(ans, tmp)
            next = P[next]
            r -= 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!

n,k=map(int,input().split())

p=list(map(lambda x:int(x)-1,input().split()))
c=list(map(int,input().split()))

lps=[]
vtd=[False]*n
for i in range(n):
    if vtd[i]:continue
    now=p[i]
    vtd[now]=True
    vc=set()
    vc.add(now)
    while now!=i:
        now=p[now]
        vtd[now]=True
        vc.add(now)
    point=0
    for v in vc:
        point+=c[v]
    lps.append((list(vc),point))

anslist=[]
for lp in lps:
    loop=lp[0]
    ls=len(loop)
    point=lp[1]
    if point<=0:
        ans=max(c)
        for first in loop:
            tmp=0
            now=first
            for j in range(min(k,ls)):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans)

        

    if point>0:
        
        ans=max(c)
        for first in loop:
            tmp=0
            now=first
            for j in range(k%ls+ls+ls):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans+point*(k//ls-2))
        # s=vc[100000]
print(max(anslist))

Submission status: Wrong Answer

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

ans=max(c)
if ans<0:
    print(ans)
    exit()

for i in range(n):
    nxt=i
    lp=[]
    while 1:
        nxt=p[nxt]
        lp.append(nxt)
        if nxt==i:
            break
    rst=k%len(lp)
    nxt=i
    wks=0
    lpm=0
    lpm2=0
    for j in range(n):
        nxt=p[nxt]
        wks+=c[nxt]
        if j<rst:
            lpm=max(lpm,wks)
        lpm2=max(lpm2,wks)

    lpc=sum(c[x] for x in lp)
    ans=max(ans,(k//len(lp))*lpc+lpm,((k//len(lp))-1)*lpc+lpm2)
print(ans)

Submission status: Wrong Answer

Solution code:
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))

n,k=nii()
p=lnii()
c=lnii()

ans=-10**18
for i in range(n):
  ini_x=i
  x=i

  tot=0
  c_l=[]
  while True:
    x=p[x]-1
    c_l.append(c[x])
    if x==ini_x:
      break

  if sum(c_l)<0:
    ans=max(ans,max(c_l))
  else:
    num=k//len(c_l)
    num-=1
    t_ans=sum(c_l)*num
    zan=k-(num*len(c_l))
    for j in range(zan):
      x=p[x]-1
      t_ans+=c[x]
      ans=max(ans,t_ans)

print(ans)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!

n,k=map(int,input().split())

p=list(map(lambda x:int(x)-1,input().split()))
c=list(map(int,input().split()))

lps=[]
vtd=[False]*n
for i in range(n):
    if vtd[i]:continue
    now=p[i]
    vtd[now]=True
    vc=set()
    vc.add(now)
    while now!=i:
        now=p[now]
        vtd[now]=True
        vc.add(now)
    point=0
    for v in vc:
        point+=c[v]
    lps.append((list(vc),point))

anslist=[]
for lp in lps:
    loop=lp[0]
    ls=len(loop)
    point=lp[1]
    if point<=0:
        ans=max(c)
        for first in loop:
            tmp=0
            now=first
            for j in range(min(k,ls)):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans)

        

    if point>0:
        
        ans=max(c)
        for first in loop:
            tmp=0
            now=first
            for j in range(k%ls+ls):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans+point*(k//ls-1))
        # s=vc[100000]
print(max(anslist))

Submission status: Wrong Answer

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

score = []
for start in range(N):
  position = start
  score_tmp = []

  for k in range(K):
    position = P[position] - 1
    score_tmp.append(C[position])
    score.append(sum(score_tmp))

    if position == start:
      score_per_round = sum(score_tmp)
      length_per_round = len(score_tmp)
      nrounds = K // length_per_round
      mod = K % length_per_round

      if score_per_round > 0:
        for i_mod in range(mod):
          score.append(nrounds * score_per_round + sum(score_tmp[:i_mod + 1]))
      else:
        for i_length in range(length_per_round):
          score.append(score_per_round + sum(score_tmp[:i_length + 1]))
      break

print(max(score))

Submission status: Wrong Answer

Solution code:
import sys


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

def smax(b,nn):
    cc=0
    bmax9=-10**20
    for i in range(nn):
#       print(b,p[b])
       b=p[b]
       cc+=c[p[b]]
#       print(i,cc,bmax9)
       bmax9=max(bmax9,cc)
    return bmax9,cc

if k<=n:
    bmax=-10**20
    for st in range(n):
        bmax9,cc=smax(st,k)
        bmax=max(bmax,bmax9)
    print(bmax)
    sys.exit()
    
bmax=-10**20
for st in range(n):
    cc=0
    b=st
    chk=[-1]*n
    chk[st]=0
    for i in range(n):
       b=p[b]
       if chk[b]>=0:
           break
       else:
           chk[b]=i+1

#    ki=chk[b]+1
#    kc=(i+1)-chk[b]
#    k2=(k-ki)%kc+ki
    ki=chk[b]
    kc=i-chk[b]+1
    k2=(k-ki-1)%kc+ki+1
#    print(st,ki,kc,k2)
    bmax1,cc1=smax(st,ki+kc)
    bmax0,cc0=smax(st,ki)
    ccc=cc1-cc0
    if ccc<=0:
        bmax9,cc=smax(st,k2)
    else:
        bmax9,cc=smax(st,k2+kc)
        bmax9+=ccc*((k-ki-1)//kc-1)

    bmax=max(bmax,bmax9)
print(bmax)

Submission status: Wrong Answer

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

score = []
for start in range(N):
  position = start
  score_tmp = []

  for k in range(K):
    position = P[position] - 1
    score_tmp.append(C[position])
    score.append(sum(score_tmp))

    if position == start:
      score_per_round = sum(score_tmp)
      length_per_round = len(score_tmp)
      nrounds = K // length_per_round
      mod = K % length_per_round

      if score_per_round > 0:
        for i_mod in range(mod):
          score.append(nrounds * score_per_round + sum(score_tmp[:i_mod + 1]))
      else:
        for i_length in range(length_per_round):
          score.append(sum(score_tmp[:i_length + 1]))
      
      break

print(max(score))

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
from collections import deque, defaultdict
def main():
    n, ko = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    scores_all = deque()
    for k1 in range(n):
        scores = deque()
        kita = defaultdict(int)
        kita[k1] = ko
        cnt = ko - 1
        koko = p[k1] - 1
        scores.append(c[koko])
        kita[koko] = cnt
        cycle_long = n
        while cnt:
            cnt -= 1
            koko = p[koko] - 1
            scores.append(c[koko])
            if kita[koko]:
                cycle_long = kita[koko] - cnt
                break
            else:
                kita[koko] = cnt
        scores_a = tuple(accumulate(scores))
        
        if cnt:
            if scores_a[-1] > 0:
                kaisuu = ko // cycle_long
                s = scores_a[-1] * kaisuu
                amari = ko % cycle_long
                if amari:
                    t = max(0, max(scores_a[:amari]))
                    s += t
                scores_all.append(s)
            else:
                scores_all.append(max(scores_a))
        else:
            scores_all.append(max(scores_a))
    print(max(scores_all))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys


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

def smax(b,nn):
    cc=0
    bmax9=-10**20
    for i in range(nn):
#       print(b,p[b])
       b=p[b]
       cc+=c[p[b]]
#       print(i,cc,bmax9)
       bmax9=max(bmax9,cc)
    return bmax9,cc

if k<=n:
    bmax=-10**20
    for st in range(n):
        bmax9,cc=smax(st,k)
        bmax=max(bmax,bmax9)
    print(bmax)
    sys.exit()
    
bmax=-10**20
for st in range(n):
    cc=0
    b=st
    chk=[-1]*n
    chk[st]=0
    for i in range(n):
       b=p[b]
       if chk[b]>=0:
           break
       else:
           chk[b]=i+1

    ki=chk[b]+1
    kc=(i+1)-chk[b]
    k2=(k-ki)%kc+ki
#    ki=chk[b]
#    kc=i-chk[b]+1
#    k2=(k-ki-1)%kc+ki+1
#    print(st,ki,kc,k2)
    bmax1,cc1=smax(st,ki+kc)
    bmax0,cc0=smax(st,ki)
    ccc=cc1-cc0
    if ccc<=0:
        bmax9,cc=smax(st,k2)
    else:
        bmax9,cc=smax(st,k2+kc)
        bmax9+=ccc*((k-ki)//kc-1)

    bmax=max(bmax,bmax9)
print(bmax)

Submission status: Wrong Answer

Solution code:
import sys


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

def smax(b,nn):
    cc=0
    bmax9=-10**20
    for i in range(nn):
#       print(b,p[b])
       b=p[b]
       cc+=c[p[b]]
#       print(i,cc,bmax9)
       bmax9=max(bmax9,cc)
    return bmax9,cc

if k<=n:
    bmax=-10**20
    for st in range(n):
        bmax9,cc=smax(st,k)
        bmax=max(bmax,bmax9)
    print(bmax)
    sys.exit()
    
bmax=-10**20
for st in range(n):
    cc=0
    b=st
    chk=[-1]*n
    chk[st]=0
    for i in range(n):
       b=p[b]
       if chk[b]>=0:
           break
       else:
           chk[b]=i+1

    ki=chk[b]+1
    kc=(i+1)-chk[b]
    k2=(k-ki)%kc+ki
#    ki=chk[b]
#    kc=i-chk[b]+1
#    k2=(k-ki-1)%kc+ki+1
    print(st,ki,kc,k2)
    bmax1,cc1=smax(st,ki+kc)
    bmax0,cc0=smax(st,ki)
    ccc=cc1-cc0
    if ccc<=0:
        bmax9,cc=smax(st,k2)
    else:
        bmax9,cc=smax(st,k2+kc)
        bmax9+=ccc*((k-ki)//kc-1)

    bmax=max(bmax,bmax9)
print(bmax)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
from collections import deque, defaultdict
def main():
    n, ko = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    scores_all = deque()
    for k1 in range(n):
        scores = deque()
        kita = defaultdict(int)
        kita[k1] = ko + 1
        cnt = ko
        koko = p[k1] - 1
        scores.append(c[koko])
        kita[koko] = cnt
        cycle_long = n
        while cnt:
            cnt -= 1
            koko = p[koko] - 1
            scores.append(c[koko])
            if kita[koko]:
                cycle_long = kita[koko] - cnt
                break
            else:
                kita[koko] = cnt
        scores_a = tuple(accumulate(scores))
        if cnt:
            if scores_a[-1] > 0:
                kaisuu = ko // cycle_long
                s = scores_a[-1] * kaisuu
                amari = ko % cycle_long
                if amari:
                    t = max(0, max(scores_a[:amari]))
                    s += t
                scores_all.append(s)
            else:
                scores_all.append(max(scores_a))
        else:
            scores_all.append(max(scores_a))
    print(max(scores_all))

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

score = []
for start in range(N):
  position = start
  score_tmp = []

  for k in range(K):
    position = P[position] - 1
    score_tmp.append(C[position])
    score.append(sum(score_tmp))

    if position == start:
      score_per_round = sum(score_tmp)
      length_per_round = len(score_tmp)
      nrounds = K // length_per_round
      mod = K % length_per_round

      if score_per_round > 0:
        for i_mod in range(mod):
          score.append(nrounds * score_per_round + sum(score_tmp[:i_mod + 1]))
      else:
        for i_round in range(nrounds):
          score.append(sum(score_tmp[:i_round + 1]))
      
      break

print(max(score))

Submission status: Wrong Answer

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

ans=max(c)
if ans<0:
    print(ans)
    exit()

for i in range(n):
    nxt=i
    lp=[]
    while 1:
        nxt=p[nxt]
        lp.append(nxt)
        if nxt==i:
            break
    rst=k%len(lp)
    nxt=i
    wks=0
    lpm=0
    for _ in range(rst):
        nxt=p[nxt]
        wks+=c[nxt]
        lpm=max(lpm,wks)
    lpc=0
    lpc2=0
    for j in lp:
        lpc+=c[j]
        lpcs=max(lpc2,lpc)
    if k<len(lp):
        lpc2=0

    ans=max(ans,(k//len(lp))*lpc+lpm,lpc2)
print(ans)