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**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) > 0:
        for j in range(len(weight)-1):
          weight[j+1] += weight[j]
        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:
"""
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")

    # ループを探す
    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), 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:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
n,k = ma()
Pt = lma()
P = [p-1 for p in Pt]
C = lma()
class unionfind():
    def __init__(self,n):
        self.par = list(range(n))
        self.size = [1]*n
        self.rank = [0]*n

    def root(self,x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.root(self.par[x])
            return self.par[x]

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

    def unite(self,x,y):
        x = self.root(x)
        y = self.root(y)
        if x==y:return
        else:
            if self.rank[x] < self.rank[y]:
                 x,y = y,x
            if self.rank[x] == self.rank[y]:
                self.rank[x]+=1
            self.par[y] = x
            self.size[x] +=self.size[y]
    def get_size(self,x):
        x = self.root(x)
        return self.size[x]
uf = unionfind(n)
for i in range(n):
    uf.unite(i,P[i])

def score(x):#xからスタートしたスコア
    l = uf.get_size(x)
    p,r = divmod(k,l)
    tmp = [0 for i in range(l)]#一回の累積gain
    if p==0:#ループを回れない場合
        xt=x
        ret = 0
        mx = -10*15
        for i in range(r):
            nex = P[xt]
            ret+=C[nex]
            xt = nex
            mx = max(mx,ret)
        return mx
    #ループを回れる場合
    gain_cycle = 0
    xt=x
    ret = 0
    for i in range(l):
        nex = P[xt]
        gain_cycle +=C[nex]
        ret+=C[nex]
        tmp[i] = ret
        xt = nex
    if gain_cycle>=0:
        ret = -10**10
        tval = 0
        for i in range(l):
            if i<=r-1:
                tval=tmp[i] + gain_cycle*p
            else:
                tval=tmp[i] + gain_cycle*(p-1)
            ret = max(ret,tval)
        return ret
    else:
        return max(tmp)

        #print(ret,"ret")

ans = -10**15
for i in range(n):
    ans = max(ans,score(i))
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
    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),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 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)
        continue
        if tmp_sum_list[p-1][0]<=0:
            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])
            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(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

Submission status: Wrong Answer

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

route = {}
point = {}

for idx, p in enumerate(P):
    route[idx+1] = p
    point[p] = C[p-1]

all_max = point[1]
for origin_start in range(1, N+1):
    visit = set()
    visit.add(origin_start)
    now_point = 0
    max_point = point[origin_start]
    start = origin_start
    # print(start)
    for k in range(K):
        now_point += point[start]
        max_point = max(max_point, now_point)
        start = route[start]
        if start in visit:
            roup_count = k + 1
            if now_point >= 0:
                now_point *= (K // roup_count)
                start = origin_start
                for _ in range(K % roup_count):
                    now_point += point[start]
                    max_point = max(max_point, now_point)
                    start = route[start]
            break
        visit.add(start)
    # print(k, now_point, start, K % k)
    # roup_count = k + 1
    # if now_point >= 0:
    #     now_point *= (K // roup_count)
    #     start = origin_start
    #     for k in range(K % roup_count):
    #         now_point += point[start]
    #         max_point = max(max_point, now_point)
    #         start = route[start]
    # print(k, start, now_point)

    all_max = max(max_point, all_max)
print(all_max)

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=-float("inf")

for start in range(N):
    cur=P[start]
    scores=[C[cur]]
    for _ in range(K):
        if cur==start:
            break
        cur = P[cur]
        scores.append(C[cur]+scores[-1])


    
    #no_loop_sum= max(scores[:K])
    #remain_hops=K-scores.index(no_loop_sum)-1
    #if scores[-1]>0:
    #    loops=remain_hops//len(scores)
    #else:
    #    loops=0
    #ans=max(ans,no_loop_sum+scores[-1]*loops)

    
    for goal in range(len(scores)):
        no_loop_sum=scores[goal]
        remain_hops=K-goal-1
        remain_hops=K-1

        if scores[-1]>0:
            loops=remain_hops//len(scores)
        else:
            loops=0
        ans=max(ans,no_loop_sum+scores[-1]*loops)
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 <= 50000:
    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
        if amari == 0:
            new_ans = max(new_ans, value*shou)
            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()))
s=[[0 for _ in range(2)] for _ in range(n)]
for i in range(n):
    cnt=0
    now=i
    while True:
        now=(p[now]-1)
        s[i][0]+=c[now]
        cnt+=1
        if now==i:
            break
    s[i][1]=cnt
ans=-(10**16)
for j in range(n):
    if s[j][0]>0 and k//s[j][1]>0: #何回か回る
        cnt1,cnt2=k,k
        a=k//s[j][1] #最大周回数
        score1=(a*s[j][0])
        score2=((a-1)*s[j][0])
        cnt1-=a*s[j][1]
        now=j
        pscore1=0
        pscore_max1=0
        for x in range(cnt1):
            now=(p[now]-1)
            pscore1+=c[now]
            pscore_max1=max(pscore_max1,pscore1)
        score1+=pscore_max1
        
        score_max=score1
    else:
        now=j
        score=0
        score_max=c[p[now]-1]
        for x in range(min(k,s[j][1])):
            now=(p[now]-1)
            score+=c[now]
            score_max=max(score_max,score)
    ans=max(ans,score_max)
print(ans)

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self, num):
        self.table = [-1 for _ in range(num)]

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

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

        if s1 != s2:
            if self.table[s1] <= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
            return True
        return False

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

u = UnionFind(N)
for i in range(N):
    u.union(i,P[i])

ans = max(C)
for i in range(N):
    s = i
    x = 0
    for j in range(min(N,K)):
        s = P[s]
        x += C[s]
        ans = max(ans,x)

for i in range(N):
    l = []
    for j in range(N):
        if u.find(i)==u.find(j):
            l.append(C[j])
    x = sum(l)*(K//len(l))
    for j in range(K%len(l)):
        s = P[s]
        x += C[s]
        ans = max(ans,x)

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

route = {}
point = {}

for idx, p in enumerate(P):
    route[idx+1] = p
    point[p] = C[p-1]

all_max = point[1]
for origin_start in range(1, N+1):
    visit = set()
    visit.add(origin_start)
    now_point = 0
    max_point = point[origin_start]
    start = origin_start
    # print(start)
    for k in range(K):
        now_point += point[start]
        max_point = max(max_point, now_point)
        start = route[start]
        if start in visit:
            roup_count = k + 1
            if now_point >= 0:
                now_point *= (K // roup_count)
                start = origin_start
                for k in range(K % roup_count + 1):
                    now_point += point[start]
                    max_point = max(max_point, now_point)
                    start = route[start]
            break
        visit.add(start)
    # print(k, now_point, start, K % k)
    # roup_count = k + 1
    # if now_point >= 0:
    #     now_point *= (K // roup_count)
    #     start = origin_start
    #     for k in range(K % roup_count):
    #         now_point += point[start]
    #         max_point = max(max_point, now_point)
    #         start = route[start]
    # print(k, start, now_point)

    all_max = max(max_point, all_max)
print(all_max)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

n, k = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

P = [p - 1 for p in P]
SB = defaultdict(int)

# Pの要素の中で循環するモノ同士をまとめる
sep = []
visited = [0] * n
for i in range(n):
  s = i
  box = []
  while visited[s] == 0:
    box.append(s)
    visited[s] = 1
    s = P[s]
  if box != []:
    sep.append(box)

ans = - 10 ** 19
for sp in sep:
  sumC = sum([C[i] for i in sp]) 
  sn = len(sp)

  if sumC > 0:
    d, mk = divmod(k, sn)
    if d > 0:
      pscore = (d - 1) * sumC
      mk += sn 
    else:
      pscore = 0
  else:
    mk = min(k, sn * 2)
    pscore = 0

  for p in sp: 
    cnt = 0
    score = 0
    mv = - 10 ** 19
    s = p
    while cnt < mk:
      score += C[s]
      s = P[s]
      cnt += 1
      mv = max(mv, score)
    
    SB[p] = mv

  ans = max(ans, max(SB.values()) + pscore)
  
print(ans)

Submission status: Wrong Answer

Solution code:
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), 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 = tuple(map(lambda x: int(x)-1, input().split()))
C = tuple(map(int, input().split()))

from collections import deque
ans = -2*10**9
for i in range(n):
    q = deque([[i, 0]])
    scores = []
    while True:
        p, score = q.popleft()
        scores.append(score)
        if p == i:
            break
        q.append([P[p], score+C[p]])

    if scores[-1] < 0:
        if k < len(scores):
            ans = max(ans, max(scores[:k]))
        else:
            ans = max(ans, max(scores))
    else:
        kk, r = divmod(k, len(scores))
        if r == 0:
            ans = max(ans, kk*scores[-1], (kk-1)*scores[-1] + max(scores))
        else:
            ans = max(ans, kk*scores[-1] + max(scores))
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()))

dummy=set()
loop=[]
X=set(range(N))
while len(dummy)!=N:
  a=[]
  k=min(X-dummy)
  a.append(k)
  dummy.add(k)
  l=P[k]-1
  while l!=k:
    a.append(l)
    dummy.add(l)
    l=P[l]-1
  loop.append(a)

ans=-(10**300)
for l in loop:
  temp=0
  s=len(l)
  ssum=0
  k=0
  for i in range(s):
    ssum+=C[l[i]]
  if ssum>0:
    temp+=(K//s)*ssum
    k=K-(K//s)*s
  else:
    k=min(K,s)
  kmax=-(10**300)
  for ii in range(1,k+1):
    for jj in range(s):
      tempscore=temp
      for kk in range(ii):
        tempscore+=C[l[(jj+kk)%s]]
      if tempscore>kmax:
        kmax=tempscore
  if kmax>ans:
    ans=kmax
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 15 17:30:06 2020

@author: divyarth
"""

import sys
import heapq
import math

#sys.setrecursionlimit(100000)
#input=sys.stdin.readline
#print=sys.stdout.write

from collections import deque
from collections import defaultdict
from collections import Counter

modH=int(10**9)+7
I=lambda : list(map(int,input().split(' ')))
def PRINT(lst,sep=' '): print(sep.join(map(str,lst)))

n,k=I()
PP=I()
c=I()
graph=[[] for i in range(n)]
for p in range(n):
    graph[p].append(PP[p]-1)
ans=[]
for start in range(n):
    visited=[0 for i in range(n)]
    node=start
    cycle=[]
    while not visited[node]:
        visited[node]=1
        cycle.append(c[node])
        node=graph[node][0]
    num_steps=k
    s=sum(cycle)*(k//len(cycle)) if k//len(cycle)>0 else 0
    
    if s<0:
        num_steps=0
        s=0
    else:
        num_steps=k//len(cycle)
        
    cum_sum=[0]
    for sss in cycle: cum_sum.append(cum_sum[-1]+sss)    
    ns=0
    ss=0
    for j in range(k%len(cycle)):
        if cum_sum[j+1]>ss:
            ss=cum_sum[j+1]
            ns=j+1
    num_steps+=ns
    if num_steps>=1:
        ans.append(s+ss)
    else:
        ans.append(c[start])
print(max(ans))

Submission status: Wrong Answer

Solution code:
#import numpy as np
#import math
#from decimal import *
#from numba import njit

#@njit
def main():
    N,K = map(int, input().split())
    P = list(map(lambda s: int(s)-1, input().split()))
    C = list(map(int, input().split()))

    m = min(C)
    loop = [(-1,[]) for _ in range(N)]
    for i in range(N):
        if loop[i][0] == -1:
            n = i
            visited = [-1]*N
            c = 0
            S = []
            while loop[n][0] == -1 and visited[n] < 0:
                loop[n] = (0,0)
                visited[n] = c
                c += 1
                n = P[n]
                if len(S) == 0:
                    S += C[n],
                else:
                    S += (S[-1] + C[n]),
            
            if visited[n] >= 0:
                p = n
                if visited[n] > 0:
                    loopS = list(map(lambda a: a-S[visited[n]-1], S[visited[n]:]))
                else:
                    loopS = S
                loop[p] = (len(loopS), loopS)
                p = P[p]
                c = 1
                while p != n:
                    loopS = list(map(lambda a: a-loopS[0], loopS[1:])) + [loopS[-1]]
                    loop[p] = (len(loopS), loopS)
                    c += 1
                    p = P[p]

        pre = 0
        n = i
        c = 0
        if loop[i][0] == 0:
            while loop[n][0] == 0 and c < K:
                pre += C[P[n]]
                m = max(m, pre)
                c += 1
                n = P[n]
        
        count = (K - c) // loop[n][0]
        rest = (K - c) % loop[n][0]
        l = loop[n][1][:rest]
        r = loop[n][1][rest:]
        if len(l) > 0:
            m = max(m, max(l)+loop[n][1][-1]*count + pre)
        if len(r) > 0:
            m = max(m, max(r)+loop[n][1][-1]*(count-1) + pre)

    print(m)

main()

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

p = [i-1 for i in p]
import numpy as np
tuuka_id = []

point_list = []

for mass in range(n):
  score = 0
  scorelist = []
  move_cnt = 0
  st_mass = mass
  if mass in tuuka_id:
    continue
  
  tuuka_id.append(mass)
  while True:
    mass = p[mass]
    #print(mass, c[mass])
    tuuka_id.append(mass)
    score += c[mass]
    scorelist.append( c[mass] )
    move_cnt += 1
    
    if mass == st_mass:
      break
  k_res = k % move_cnt
  if k_res == 0:
    k_res = move_cnt
    
  scorel2 = scorelist + scorelist

  res_val = max([ np.cumsum(scorel2[i:i+k_res]).max() for i in range( len(scorelist) )])
  if k_res == 0:
    mul = max(0,(k // move_cnt-1))
  else:
    mul = max(0,(k // move_cnt))
  
  point_list.append( max( score, score * mul, res_val, score*mul + res_val ) )
  
print(point_list)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
P = list((map(lambda a: int(a)-1, input().split())))
C = list(map(int,input().split()))
checked = [True] * N
scores = []
res = - 10 ** 60
for i in range(N):
    if checked:
        current = i
        score = []
        while checked[current]:
            checked[current] = False
            Next = P[current]
            score.append(C[Next])
            current = Next
        if len(score) > 0:
            scores.append(score)
for s in scores:
    l = len(s)
    Sum = sum(s)
    s = s+s
    wa = [0] * (l+1)
    kukan2 = K % l
    loop2 = K // l
    for kukan in range(1,l+1):
        if kukan2 < kukan:
            loop = loop2 -1
        else:
            loop = loop2
        wa = [0] * (l+kukan+1)
        for i in range(l+kukan):
            wa[i+1] = wa[i] + s[i]
        Max = - 10 ** 60
        for i in range(l):
            Max = max(Max,wa[i+kukan]-wa[i])
        res = max(res, Sum * loop + Max,Max)

print(res)

Submission status: Wrong Answer

Solution code:

#!/usr/bin/python
# -*- coding: utf-8 -*-

# def
def int_mtx(N):
    x = []
    for _ in range(N):
        x.append(list(map(int,input().split())))
    return x

def str_mtx(N):
    x = []
    for _ in range(N):
        x.append(list(input()))
    return x

def int_map():
    return map(int,input().split())

def int_list():
    return list(map(int,input().split()))

def print_space(l):
    return print(" ".join([str(x) for x in l]))

# import
import numpy as np



# main code
N,K = int_map()
P = int_list()
C = int_list()

if max(C) <= 0:
    print(max(C))
    exit()

S = np.zeros((N+1,N+1))

for i in range(0,N):
    now = i
    for j in range(0,N):
        next = P[now]-1
        S[i+1][j+1] = S[i+1][j]+C[next]
        now = next

sc = sum(C)

if sc <= 0:
    if K >= N:
        print(np.max(S[1:,1:]))
        exit()
    else:
        print(np.max(S[1:,1:K+1]))
        exit()
else:
    if K <= N:
        print(np.max(S[1:,1:K+1]))
        exit()
    else:
        a = K//N
        nc = sc*a
        rest = K%N
        print(nc + np.max(S[1:,1:rest+1]))
        exit()

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 = []
    k = 0
    visited = [-1]*N
    for r in range(N):
        S.append(C[l])
        visited[l] = r
        l = P[l] - 1
        if visited[l] != -1:
            k = r - visited[l] + 1
            break
    r += 1
    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
"""