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, math

def calcweight_tree(N_vertices, edges, times, inf):

    """
    edges: [start, dest, cost] -> [cost, start, end]
    """

    distance = 0

    passed = [False] * N_vertices
    parents = [i for i in range(N_vertices)]

    travel_max = -inf
    for i in range(N_vertices):
        if(passed[i] == False):
            distance = 0
            left = i
            costs = [0]
            cost_one = []
            min_distance = inf
            while(True):
                passed[left] = True
                dest = edges[left][2]
                cost = edges[dest][0]
                if(parents[dest] != parents[left]):
                    parents[dest] = parents[left]
                    costs.append(costs[-1] + cost)
                    cost_one.append(cost)
                    left = dest
                    if(min_distance > cost):
                        min_distance = cost
                else:
                    period = len(costs)
                    increase_period = costs[-1]+cost
                    cost_one.append(cost)
                    break
            # 2 period項準備
            for j in range(period):
                costs.append(costs[j]+increase_period)

            remainder = times%period
            times_period = times//period
            if(remainder==0):
                remainder+= period
                times_period -= 1
            if(remainder==1):
                maxvalue = max(cost_one)
                if(increase_period <=0):
                    travel_max = max(maxvalue, travel_max)
                else:
                    travel_max = max(maxvalue+times_period * increase_period, travel_max)
            else:
                #[1, remainder]
                maxvalue = -inf
                for i_start in range(1, period+1):
                    maxvalue_candidate = max(costs[i_start:remainder+i_start])
                    maxindex = costs[i_start:remainder+i_start].index(maxvalue_candidate)+i_start
                    if(maxvalue_candidate-costs[i_start-1]>maxvalue):
                        maxvalue = maxvalue_candidate-costs[i_start-1]
                        #print(costs, maxvalue, maxindex, i_start)


                #print(i, index_start, period, increase_period, costs)
                #print("  R, P", remainder, times_period)
                if(period > times or increase_period<= 0):
                    travel_max = max(maxvalue, travel_max)
                else:
                    travel_max = max(maxvalue+times_period * increase_period, travel_max)





    return travel_max







if(__name__ == "__main__"):
    """
    N = int( input().strip() )
    Length = list( map(int, input().strip().split() ) )

    edges = [ [] for _ in range(N+2) ]
    for i in range(N):
        edges[0].append([0, i]) #[cost, edge]
    for i in range(1, N+1):
        edges[i].append([0, N+1])
    for i in range(N):
        edges[i].append([ CList[i]*(-1), PList[i] ])
    """
    N, K= map(int, input().strip().split() )
    PList = list( map(int, input().strip().split() ) )
    CList = list( map(int, input().strip().split() ) )
    inf = 10**6

    """
    N_vertices = 2+N
    """
    N_vertices = N

    edges3 = []
    costs = []
    for i in range(N):
        edges3.append([ CList[i], i, PList[i]-1 ])

    weight = calcweight_tree(N_vertices, edges3, K, inf)

    #weight= calcweight_bellman_ford(N_vertices, 0, edges3, K+2, cost, inf)


    print( weight)

Submission status: Wrong Answer

Solution code:
def read_input():

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

    return n, k, p, c

def solve_i(i, k, p, c, n):
    
    points = 0
    maxi = float('-Inf')

    s = i
    i = p[i]
    t = 0
    while i != s and t < k:
        
        points += c[i]
        i = p[i]
        t += 1
        maxi = max(maxi, points)

    if k == t:
        return maxi

    points += c[i]
    maxi = max(maxi, points)
    t += 1

    if points < 0:
        return maxi
    else:
        cycles = k // t
        remainder = k % t

        potential = points * cycles
        if remainder != 0:
            tmp_max = float('-Inf')
            i = s
            tmp_points = 0
            for _ in range(remainder):
                tmp_points += c[i]
                i = p[i]
                tmp_max = max(tmp_max, tmp_points)
            potential += tmp_max

        return max(maxi, potential)

def solve(n, k, p, c):

    maxi = float('-Inf')
    for i in range(n):
        maxi = max(maxi, solve_i(i, k, p, c, n))

    return maxi


print(solve(*read_input()))

Submission status: Wrong Answer

Solution code:
import sys, math

def calcweight_tree(N_vertices, edges, times, inf):

    """
    edges: [start, dest, cost] -> [cost, start, end]
    """

    distance = 0

    passed = [False] * N_vertices


    travel_max = -inf
    for i in range(N_vertices):
        distance = 0
        left = i
        costs = [0]
        cost_one = []
        parents = [i for i in range(N_vertices)]
        while(True):
            dest = edges[left][2]
            cost = edges[dest][0]
            if(parents[dest] != parents[left]):
                parents[dest] = parents[left]
                costs.append(costs[-1] + cost)
                cost_one.append(cost)
                left = dest
            else:
                period = len(costs)
                increase_period = costs[-1]+cost
                cost_one.append(cost)
                break
        # 2 period項準備
        for j in range(period):
            costs.append(costs[j]+increase_period)

        remainder = times%period
        times_period = times//period
        if(remainder==0):
            remainder+= period
            times_period -= 1
        maxvalue = max(costs[:remainder])
        if(increase_period <=0):
            travel_max = max(maxvalue, travel_max)
        else:
            travel_max = max(maxvalue+times_period * increase_period, travel_max)
    





    return travel_max







if(__name__ == "__main__"):
    """
    N = int( input().strip() )
    Length = list( map(int, input().strip().split() ) )

    edges = [ [] for _ in range(N+2) ]
    for i in range(N):
        edges[0].append([0, i]) #[cost, edge]
    for i in range(1, N+1):
        edges[i].append([0, N+1])
    for i in range(N):
        edges[i].append([ CList[i]*(-1), PList[i] ])
    """
    N, K= map(int, input().strip().split() )
    PList = list( map(int, input().strip().split() ) )
    CList = list( map(int, input().strip().split() ) )
    inf = 10**6

    """
    N_vertices = 2+N
    """
    N_vertices = N

    edges3 = []
    costs = []
    for i in range(N):
        edges3.append([ CList[i], i, PList[i]-1 ])

    weight = calcweight_tree(N_vertices, edges3, K, inf)

    #weight= calcweight_bellman_ford(N_vertices, 0, edges3, K+2, cost, inf)


    print( weight)

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
        S = 0
        while grp[curr] == -1:
            grp[curr] = gid
            cycl.append(C[curr])
            S += C[curr]
            curr = P[curr]

        score = 0

        L = len(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 max(cycl)
        for right in range(L + 1):
            for rev_right in range(L + 1):
                if (score or right != 0 or rev_right != 0) and (
                        right + rev_right <= K):
                    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:
n,k=[int(i) for i in raw_input().split()]
p=[int(i)-1 for i in raw_input().split()]
c=[int(i) for i in raw_input().split()]
maxx=-10**18
for i in range(n):
  ct=0;j=0;pos=i
  v=[0]*n
  arr=[]
  while j<k:
    if(v[pos]==1):
  	    break
    v[pos]=1
    ct+=c[pos]
    pos=p[pos]
    arr.append(ct)
    j+=1
  val=0
  if(ct>0):
  	val=ct*((k-j)/j)
  else:
  	val=0
  k1=k
  k1%=j
  k1+=j
  for i1 in range(len(arr)):
  	if(k1-i1>j):
  	    maxx=max(maxx,val+ct+arr[i1])
  	else:
  	    maxx=max(maxx,val+arr[i1])
print maxx

Submission status: Wrong Answer

Solution code:
import sys, math

def calcweight_tree(N_vertices, edges, times, inf):

    """
    edges: [start, dest, cost] -> [cost, start, end]
    """

    distance = 0

    passed = [False] * N_vertices
    parents = [i for i in range(N_vertices)]

    travel_max = -inf
    for i in range(N_vertices):
        if(passed[i] == False):
            distance = 0
            left = i
            costs = [0]
            cost_one = []
            min_distance = inf
            while(True):
                passed[left] = True
                dest = edges[left][2]
                cost = edges[dest][0]
                if(parents[dest] != parents[left]):
                    parents[dest] = parents[left]
                    costs.append(costs[-1] + cost)
                    cost_one.append(cost)
                    left = dest
                    if(min_distance > cost):
                        min_distance = cost
                else:
                    period = len(costs)
                    increase_period = costs[-1]+cost
                    cost_one.append(cost)
                    break
            # 2 period項準備
            for j in range(period):
                costs.append(costs[j]+increase_period)

            remainder = times%period
            times_period = times//period
            if(remainder==0):
                remainder+= period
                times_period -= 1
            if(remainder==1):
                maxvalue = max(cost_one)
                if(increase_period <=0):
                    travel_max = max(maxvalue, travel_max)
                else:
                    travel_max = max(maxvalue+times_period * increase_period, travel_max)
            else:
                #[1, remainder]
                maxvalue_candidate = max(costs[1:remainder])
                maxindex = costs[1:remainder].index(maxvalue_candidate)+1

                maxvalue = maxvalue_candidate
                index_start = 0

                #candidate: 引く前
                #必要な情報: index_startとmaxvalue

                for i_start in range(1, period):
                    #[i, i+remainder]
                    if(maxindex <= i_start):
                        maxvalue_candidate = max(costs[i_start+1:i_start+remainder])
                        maxindex = costs[i_start+1:i_start+remainder].index(maxvalue_candidate) + i_start+1

                    elif(costs[i_start+remainder]>=maxvalue):
                        maxvalue_candidate =costs[i_start+remainder]
                        maxindex = i_start+remainder+1

                    if(maxvalue_candidate-costs[i_start] >= maxvalue):
                        maxvalue = maxvalue_candidate-costs[i_start]
                        index_start = i_start

                #print(i, index_start, period, increase_period, costs)
                #print("  R, P", remainder, times_period)
                if(period > times or increase_period<= 0):
                    travel_max = max(maxvalue, travel_max)
                else:
                    travel_max = max(maxvalue+times_period * increase_period, travel_max)





    return travel_max







if(__name__ == "__main__"):
    """
    N = int( input().strip() )
    Length = list( map(int, input().strip().split() ) )

    edges = [ [] for _ in range(N+2) ]
    for i in range(N):
        edges[0].append([0, i]) #[cost, edge]
    for i in range(1, N+1):
        edges[i].append([0, N+1])
    for i in range(N):
        edges[i].append([ CList[i]*(-1), PList[i] ])
    """
    N, K= map(int, input().strip().split() )
    PList = list( map(int, input().strip().split() ) )
    CList = list( map(int, input().strip().split() ) )
    inf = 10**6

    """
    N_vertices = 2+N
    """
    N_vertices = N

    edges3 = []
    costs = []
    for i in range(N):
        edges3.append([ CList[i], i, PList[i]-1 ])

    weight = calcweight_tree(N_vertices, edges3, K, inf)

    #weight= calcweight_bellman_ford(N_vertices, 0, edges3, K+2, cost, inf)


    print( weight)

Submission status: Wrong Answer

Solution code:
import sys, math

def calcweight_tree(N_vertices, edges, times, inf):

    """
    edges: [start, dest, cost] -> [cost, start, end]
    """

    distance = 0

    passed = [False] * N_vertices
    parents = [i for i in range(N_vertices)]

    travel_max = -inf
    for i in range(N_vertices):
        if(passed[i] == False):
            distance = 0
            left = i
            costs = [0]
            min_distance = inf
            while(True):
                passed[left] = True
                dest = edges[left][2]
                cost = edges[dest][0]
                if(parents[dest] != parents[left]):
                    parents[dest] = parents[left]
                    costs.append(costs[-1] + cost)
                    left = dest
                    if(min_distance > cost):
                        min_distance = cost
                else:
                    period = len(costs)
                    increase_period = costs[-1]+cost
                    break
            # 2 period項準備
            for j in range(period):
                costs.append(costs[j]+increase_period)

            remainder = times%period
            times_period = times//period
            if(remainder==0):
                remainder+= period
                times_period -= 1
            if(remainder==1):
                remainder = 2
            #[1, remainder]
            

            maxvalue_candidate = max(costs[1:remainder])
            maxindex = costs[1:remainder].index(maxvalue_candidate)+1

            maxvalue = maxvalue_candidate
            index_start = 0

            #candidate: 引く前
            #必要な情報: index_startとmaxvalue

            for i_start in range(1, period):
                #[i, i+remainder]
                if(maxindex <= i_start):
                    maxvalue_candidate = max(costs[i_start+1:i_start+remainder])
                    maxindex = costs[i_start+1:i_start+remainder].index(maxvalue_candidate) + i_start+1

                elif(costs[i_start+remainder]>=maxvalue):
                    maxvalue_candidate =costs[i_start+remainder]
                    maxindex = i_start+remainder+1

                if(maxvalue_candidate-costs[i_start] >= maxvalue):
                    maxvalue = maxvalue_candidate-costs[i_start]
                    index_start = i_start

            #print(i, index_start, period, increase_period, costs)
            #print("  R, P", remainder, times_period)
            if(period > times or increase_period<= 0):
                travel_max = max(maxvalue, travel_max)
            else:
                travel_max = max(maxvalue+times_period * increase_period, travel_max)

    return travel_max







if(__name__ == "__main__"):
    """
    N = int( input().strip() )
    Length = list( map(int, input().strip().split() ) )

    edges = [ [] for _ in range(N+2) ]
    for i in range(N):
        edges[0].append([0, i]) #[cost, edge]
    for i in range(1, N+1):
        edges[i].append([0, N+1])
    for i in range(N):
        edges[i].append([ CList[i]*(-1), PList[i] ])
    """
    N, K= map(int, input().strip().split() )
    PList = list( map(int, input().strip().split() ) )
    CList = list( map(int, input().strip().split() ) )
    inf = 10**6

    """
    N_vertices = 2+N
    """
    N_vertices = N

    edges3 = []
    costs = []
    for i in range(N):
        edges3.append([ CList[i], i, PList[i]-1 ])

    weight = calcweight_tree(N_vertices, edges3, K, inf)

    #weight= calcweight_bellman_ford(N_vertices, 0, edges3, K+2, cost, inf)


    print( weight)

Submission status: Wrong Answer

Solution code:
def read_input():

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

    return n, k, p, c

def solve_i(i, k, p, c, n):
    
    points = 0
    maxi = float('-Inf')

    s = i
    i = p[i]
    t = 0
    while i != s and t < k:
        
        points += c[i]
        i = p[i]
        t += 1
        maxi = max(maxi, points)

    points += c[i]
    maxi = max(maxi, points)

    if k == t or points <= 0:
        return maxi
    else:
        cycles = k // t
        remainder = k % t

        potential = points * cycles
        if remainder != 0:
            tmp_max = float('-Inf')
            i = s
            tmp_points = 0
            for _ in range(remainder):
                tmp_points += c[i]
                i = p[i]
                tmp_max = max(tmp_max, tmp_points)
            potential += tmp_max

        return max(maxi, potential)

def solve(n, k, p, c):

    maxi = float('-Inf')
    for i in range(n):
        maxi = max(maxi, solve_i(i, k, p, c, n))

    return maxi


print(solve(*read_input()))

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-2)//count)-1)*ans
    
    if ans22<ans:
      ans22=ans
    for i in range(k-((k-2)//count-1)*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
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-2)//count)-1)*ans
    
    if ans22<ans:
      ans22=ans
    for i in range(k-((k-2)//count-1)*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()))

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:
    # 1周目
    cumsum1 = [0]
    for x in route[1:]:
        cumsum1.append(cumsum1[-1] + C[x - 1])
    # 2周目
    for x in route:
        cumsum1.append(cumsum1[-1]+C[x-1])

    # ループ部分だけ
    cumsum2 = [0]
    for x in route:
        cumsum2.append(cumsum2[-1] + C[x - 1])

    # print(cumsum1,cumsum2)

    # ループするほど損する場合
    if cumsum2[-1] <= 0:
        # 1回以上操作をする必要があることに注意
        score = cumsum1[1:min(K + 1, len(cumsum1))]
        ans=max(ans, max(score))
    # 出来るだけループした方が得する場合
    else:
        # ループできる回数
        loop_cnt=K // len(route)
        # 最大限ループした後に残る操作回数
        spare_K=K % len(route)
        spare_score=cumsum2[1:spare_K + 2]
        max_spare_score=max(spare_score)
        # スタートの点数分は引く
        ans=max(ans, loop_cnt * cumsum2[-1] +
                  max_spare_score - C[route[0] - 1])

print(ans)

Submission status: Wrong Answer

Solution code:
import math

def split_to_loops(G):
    # G[i]: i の次の頂点(0 <= i <= |G|-1) を格納しているリストがあるとき、
    # ループ単位にリストを分割する。
    # ex) G = [1, 3, 4, 0, 2]
    # => "0 -> 1 -> 3 -> 0" というループと
    #    "2 -> 4 -> 2" というループがある
    # このメソッドでは、[[0,1,3],[2,4]]が返される

    loops = []
    _all = set(range(len(G)))

    while _all:
        s = _all.pop()
        loop = [s]
        v = G[s]
        while v != s:
            _all.remove(v)
            loop.append(v)
            v = G[v]

        loops.append(loop)

    return loops

def find_max_continued(A, n):
    # A 内で連続した1個以上n個以内の領域の合計の最大値を見つける
    # ex) A = [-2, 4, 3, -1, 2, 6, 4, 5, -3], n = 3
    #       => [6, 4, 5] の合計 =15 が最大
    # ex) A = [-2, 4, 3, -1, 2, 6, -4, 5, -3], n = 3
    #       => [2, 6] の合計 =8 が最大
    # ex) A = [-2, 4, 3, -1, 2, 6, -4, 5, -3], n = 4
    #       => [3, -1, 2, 6] の合計 =10 が最大
    # ex) A = [-2, -4, -3, -1, -2, -6, -4, -5, -3], n = 3
    #       => [-1] の合計 =-1 が最大

    # n = 1のとき
    _max = max(A)

    # n = 2以上
    L = len(A)
    for d in range(2, n+1):
        _sum = sum(A[:d])
        _max = max(_max, _sum)
        # 領域を右にずらしながら合計を計算することで、O(L) で計算できる 
        for i in range(d, L):
            _sum += A[i] - A[i-d]
            _max = max(_max, _sum)

    return _max

def find_max_in_one_loop(loop, K, C):
    # loopにおける1回以上K回以内の移動でのスコアの最大値を見つける
    L = len(loop)
    loop_c = [C[v] for v in loop] # ループに登場するマスのスコアのリスト
    # print(f'{loop_c=}')

    # 一周したときのスコア
    sum_1_loop = sum(loop_c)
    # print(f'{loop_c=}, {sum_1_loop=}')

    if sum_1_loop < 0:
        # 一周したときに負になるようなら、ループしないほうがいい
        return find_max_continued(loop_c, min(K, L))
    else:
        # 一周以上移動できない場合
        if K < L:
            return find_max_continued(loop_c, K)

        # 一周以上移動できる場合
        # できるだけループしたほうがいい

        n_loops = K // L # ループできる回数

        # ただし、スコアが [1 1 1 -2] のようになっている場合、
        # 1周するより負の数を避けて途中で終了したほうがいいので、
        # 一旦わざとループできる回数から1周分減らしておく
        n_loops -= 1
        
        score = sum_1_loop * n_loops
        K -= n_loops * L # 残りの移動回数 (L <= K < 2*L)

        # 一周未満の時のスコアの最大値
        score_no_loop = find_max_continued(loop_c, L)
        # 一周してさらにK-L回以内で移動するときのスコア
        score_loop = sum_1_loop
        if K != L:
            # print(f'{K=}, {L=}, {K-L}, {find_max_continued(loop_c, K - L)}')
            score_loop += find_max_continued(loop_c, K - L)
        # 最後、一周しないほうがいいか、一周したほうがいいか、スコアの大きいほうを選ぶ
        score += max(score_no_loop, score_loop)
        return score

def main():
    N, K = map(int, input().split())
    # P は番号を1引くことで配列で扱いやすくする
    P = list(map(lambda x: int(x)-1, input().split()))
    C = list(map(int, input().split()))

    # ループごとに分割
    # ex) P = [1, 3, 4, 0, 2]
    # => "0 -> 1 -> 3 -> 0" というループと
    #    "2 -> 4 -> 2" というループがある
    # => loops = [[0,1,3],[2,4]]
    loops = split_to_loops(P)
    # print(f'{loops=}')

    ans = -(10 ** 10)
    for loop in loops:
        # [0,1,3] などのループ単位で、1回以上K回以内の移動での最大値を見つける
        # その最大値の中からさらに最大値を見つけて、答えとする
        ans = max(ans, find_max_in_one_loop(loop, K, C))
    
    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()))

sumlist1 = [[0]*N for _ in range(N)]
walist = [[0]*N for _ in range(N)]
loopcount = [0]*N

for h in range(N):
    sumlist1[h][0] = C[h]
    walist[h][0] = C[h]
    now = h
    l = 0
    for i in range(1,N):
        now = P[now]-1

        if sumlist1[h][i-1] < 0:
            sumlist1[h][i] = C[now]
        else:
            sumlist1[h][i] += sumlist1[h][i-1] + C[now]
        walist[h][i] += walist[h][i-1] + C[now]
        
        l += 1
        if now == h:
            break
    else:
        l += 1
    loopcount[h] = l
#print(sumlist1)

maxlist = [0]*N
for i in range(N):
    T = loopcount[i]
    wa = walist[i][T-1]
    #print(wa)

    loop = K//T
    amari = K%T

    if wa >= 0:
        if loop == 0:
            if amari != 0:
                maxlist[i] = wa*loop + max(sumlist1[i][:amari])
            else:
                maxlist[i] = wa*loop
        else:
            if amari != 0:
                maxlist[i] = max(wa*loop + max(sumlist1[i][:amari]), wa*(loop-1) + max(sumlist1[i]))
            else:
                maxlist[i] = max(wa*loop, wa*(loop-1) + max(sumlist1[i]))
            

    else:
        if loop == 0:
            maxlist[i] = max(sumlist1[i][:amari])
        else:
            maxlist[i] = max(sumlist1[i])

print(max(maxlist))
#print(sumlist1)

Submission status: Wrong Answer

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

d = -10 ** 9
j = 0

i = 0
s = 0
x = []
z = []

for l in range(N):
    s = 0
    j = l
    if i in z:
        continue
    
    for i in range(K):
        s += C[j]        
        
        if s > d:
            d = s

        if not(i in x):
            x.append(j)

        j = P[j] - 1

        if j == l and s < d:
            if K-i-1 > i:
                i = i * (K-i // i)
                s = s * i
        elif j == l:
            z.extend(x)
            break
print(d)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal

INF = 1 << 100


def run():
    N, K = map(int, sysread().split())
    P = list(map(int, sysread().split()))
    C = list(map(int, sysread().split()))
    P = [p-1 for p in P]

    loops = []
    checked = [0] * N
    loop = [0]
    for i in range(N):
        current = i
        while True:
            if not checked[current]:
                checked[current] = 1
                loop.append(C[current])
                current = P[current]
            else:
                if len(loop) == 1:break
                loops.append(loop)
                loop = [0]
                break
    loopSums = []
    for loop in loops:
        val = 0
        tmp = []
        for l in loop:
            val += l
            tmp.append(val)
        loopSums.append(tmp)
    #print(loops)
    #print(loopSums)
    ans = -INF
    for loop, loopSum in zip(loops, loopSums):
        for i in range(1, len(loop)):
            val = 0
            if loopSum[-1] <= 0 or len(loop) > K:
                j = i
                max_val = -INF
                iter = 0
                while iter < K:
                    iter += 1
                    j += 1
                    if j == len(loop):
                        j = 1
                    val += loop[j]
                    max_val = max(max_val, val)
                    if i == j:
                        break
                #ans = max(ans, max_val)
                continue


            rest = K
            #if K <= len(loop) - i - 1:
            #    val += loopSum[i + K - 1] - loopSum[i]
            #    ans = max(ans, val)
            #    continue
            rest -= len(loop) - i - 1
            val += loopSum[-1] - loopSum[i]
            val += (rest // (len(loop)-1)) * loopSum[-1]
            rest = rest % (len(loop) - 1)
            if rest:
                val += max(loopSum[1:rest+1])
            ans = max(ans, val)

    print(ans)

if __name__ == "__main__":
    run()