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:
(n, k), p, c = [[*map(int, i.split())] for i in open(0)]
visit = [0] * n
visit[0] = 1
loop = [0] * n
count = a = 0
while True:
    a = p[a] - 1
    if visit[a]:
        if loop[a]:
            break
        count += c[a]
        loop[a] = 1
    visit[a] = 1

ln = sum(loop)


def solve(x, t):
    ans = c[p[x] - 1]
    l = True
    sub = 0
    while True:
        if loop[x] and l and count > 0:
            sub += t // ln * count
            t %= ln
            l = False
        if t < 1:
            ans = max(sub, ans)
            return ans
        x = p[x] - 1
        sub += c[x]
        t -= 1
        ans = max(sub, ans)


print(max(solve(i, k) for i in range(n)))

Submission status: Wrong Answer

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

ans = -float('inf')
for i in range(N):
    s = 0
    j = i
    for k in range(K):
        j = P[j]-1
        s += C[j]
        ans = max(ans, s)
        if j==i: break
    d,m = divmod(K, k+1)
    s *= d
    ans = max(ans, s)
    for k in range(m):
        j = P[j]-1
        s += C[j]
        ans = max(ans, s)

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()))
raw = []
seen = [0 for _ in range(n)]
for i in range(n):
  now = int(i)
  tmp = []
  if seen[i]:
    continue
  while seen[now] == 0:
    tmp.append(c[now])
    seen[now] = 1
    now = p[now] - 1
  raw.append(tmp)
#print(raw)
can = 0
for x in raw:
  sun = sum(x)
  l = len(x)
  x = x + x + x
  #print(x)
  now = [0]
  for y in x:
    now.append(now[-1]+y)
  #print(now)
  if sun > 0 and k >= l:
    ans = sun* (k//l-1)
    k = k % l + l
    #print(ans,k)
    maxi = 0
    for i in range(l):
      for j in range(i+1,3*l+1):
        if j - i <= k:
          maxi = max(maxi,now[j]-now[i])
    can = max(ans+maxi,can)
  else:
    maxi = 0
    for i in range(3*l+1):
      for j in range(i+1,3*l+1):
        if j - i <= k:
          maxi = max(maxi,now[j]-now[i])
    can = max(maxi,can)
if can == 0:
  print(max(c))
else:
  print(can)

Submission status: Wrong Answer

Solution code:
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations,permutations,accumulate, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
#import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
def readInts():
  return list(map(int,input().split()))
def I():
  return int(input())
n,k = readInts()
P = readInts()
C = readInts()
dic = defaultdict(int)
for i in range(n):
    dic[i+1] = P[i]
ans = -float('inf')
#print(dic)
for start in range(n):
    nya = deque()
    root = defaultdict(int)
    pya = start+1
    cnt = 0
    SUM = 0
    while root[dic[pya]] == 0 and cnt < k:
        pya = dic[pya]
        nya.append(C[pya-1])
        cnt += 1
        SUM += C[pya-1]
        root[pya] = 1
        #print('while',pya,dic[pya],SUM)
        ans = max(ans,SUM)
    if cnt < k:# まだ満たない
        need = k-cnt
        nl = len(nya)
        sumnya = sum(nya)
        a = need//nl
        SUM += sumnya * a
        ans = max(ans,SUM)
        nokori = need - nl*a
        for idx in range(nokori):
            SUM += nya[idx]
            ans = max(ans,SUM)
            #print('nokori',SUM)
    else:
        ans = max(ans,SUM)
print(ans)

Submission status: Wrong Answer

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
if K == 1:
    print(max(C))
    import sys
    sys.exit()
uf = UnionFind(N)
for i in range(N):
    uf.union(i, P[i]-1)

ans = -float("inf")
for x in uf.all_group_members().values():
    n = len(x)
    m_score = [-float("inf")] * (n+1)
    m_score[0] = 0
    sum_c = 0
    for i in x:
        tmp_score = 0
        tmp_pos = i
        sum_c += C[i]
        for j in range(n):
            tmp_pos = P[tmp_pos]
            tmp_pos -= 1
            tmp_score += C[tmp_pos]
            m_score[j+1] = max(tmp_score, m_score[j+1])
    if sum_c <= 0:
        ans = max(max(m_score[1:]), ans)
    elif K <= n:
        ans = max(ans, max(m_score[1:K+1]))
    else:
        ans = max(sum_c * (K//n) + max(m_score[:(K%n)+1]), ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2147483647)
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
# n, k = 1000, 5000
# p = [random.randint(1, n) for _ in range(n)]
# c = [random.randint(-10000, 10000) for _ in range(n)]

# ループを見つける(5000), 一周のスコアを確認
is_visit = [0 for _ in range(n)]
loop = []

def search(i, j):
    if is_visit[i] == 0:
        is_visit[i] = j
        l.append(i)
        search(p[i]-1, j)
    else:
        pass

loop_id = 1
for i in range(n):
    l = []
    search(i, loop_id)
    if len(l) != 0:
        loop.append(l)
        loop_id += 1
# print(loop)
# print(is_visit)

ans = [0 for _ in range(n)]
for i in range(n):
    # i からはじめて最大スコア
    l = loop[is_visit[i]-1] # 所属するループ
    tmp1 = 0 # ループによるスコア
    tmp_k = k
    s = 0
    for j in range(len(l)):
        s += c[l[j]]
    if s > 0 and k > len(l):
        # 回るほどお得で一周より回れる
        tmp1 += s*(tmp_k//len(l))
        tmp_k -= (tmp_k//len(l))*len(l)
    else:
        tmp_k -= (tmp_k//len(l))*len(l)
        if tmp_k == 0:
            tmp_k = len(l)
    pointer = p[i]
    tmp2 = [c[pointer-1] for _ in range(tmp_k)] # 愚直に進んだ点数
    if tmp_k != 0:
        for j in range(1, tmp_k):
            # k回目までの累積和で最大を求める
            pointer = p[pointer-1]
            tmp2[j] = tmp2[j-1] + c[pointer-1]
    # print(i, l, s, tmp_k, tmp1, tmp2)
    if len(tmp2) != 0:
        ans[i] = tmp1 + max(tmp2)
    else:
        ans[i] = tmp1
# print(ans)
print(max(ans))

Submission status: Wrong Answer

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

has_visited = [False]*N
score_max = -float('inf')

for i in range(N):
    if has_visited[i]:
        continue
    
    loop_val = []

    j = i
    while True:
        loop_val.append(C[j])
        has_visited[j] = True
        j = P[j] - 1
        if loop_val[0] == C[j]:
            break
    
    # sum_arr = [0]
    # loop_length = len(loop_val)

    # for k in range(1, loop_length + K):
    # sum_arr.append(sum_arr[k-1] + loop_val[(k - 1) % loop_length])

    # print(loop_val)

    sm = 0
    for p in range(len(loop_val)):
        sm += loop_val[p]
    
    # print(sm)
    
    loop_length = len(loop_val)
    res = -1
    s = 0
    for k in range(loop_length + K - 1):
        s = max([s + loop_val[k % loop_length], loop_val[k % loop_length]])
        res = max([res, s])
    
    if res == -1:
        res = max(loop_val)
    
    # print(res)

    if score_max < res:
        score_max = res

print(score_max)

Submission status: Wrong Answer

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

ans = -10**9
v = [False for _ in range(n)]
for i in range(n):
  j = i
  if v[j]:
    continue
  r = []
  while(v[j] == False):
    r.append(j)
    v[j] = True
    j = p[j]
  s = 0
  rr = []
  f = True
  for ri in r:
    s += c[ri]
    rr.append(c[ri])
    if c[ri] > 0:
      f = False
  if s >= 0:
    k1 = k%len(r)
    k2 = k//len(r)
    rr = rr+rr
    now = 0
    for i in range(len(rr)-k1+1):
      now = max(sum(rr[i:i+k1]),now)
    now += s*k2
  else:
    if f:
      now = -10**9
      for rri in rr:
        now = max(rri,now)
    else:
      rr = rr+rr
      a = 0
      b = 0
      now = -10**9
      while(b < len(rr)):
        if rr[a] <= 0:
          a += 1
          b += 1
        else:
          now = max(sum(rr[a:b+1]),now)
          b += 1
          if b-a > k:
            a += 1
  #print(now,r)
  ans = max(ans,now)
print(ans)

Submission status: Wrong Answer

Solution code:
def roop(i,K):
    isroop=False
    last=[-1]*N
    lastcnt=[-1]*N
    n=i
    last[n]=0
    lastcnt[n]=0
    roopp=-1#ループ1回のポイント
    cnt=0#
    rs=-1#ループ開始
    maxp=-10**30
    point=0
    while(True):
        cnt+=1
        n=P[n]
        point+=C[n]
        maxp=max(maxp,point)
        if last[n]!=-1:
            roopp=point-last[n]
            syuki=cnt-last[n]#ループ周期
            isroop=True
            rs=n
            start=last[n]
            break
        last[n]=point
        lastcnt[n]=cnt
        if cnt==K:
            break
    if not isroop:
        return  maxp
    K-=lastcnt[rs]
    roopcnt=K//syuki
    allpoint=(K//syuki)*roopp
    K%=syuki
    j=0
    n=rs
    point=0
    maxpp=0
    while(j<K):
        j+=1
        n=P[n]
        point+=C[n]
        maxpp=max(maxpp,point)
    if rs!=i:
        return max([start,start+allpoint,start+allpoint+maxpp,start+allpoint-roopp+maxpp])
    else:
        if roopcnt>1:
            return max([allpoint,allpoint+maxpp,maxp,allpoint-roopp+maxpp])
        else:
            return max([allpoint,allpoint+maxpp,maxp])
        
        
        

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

ans=-10**30
for i in range(N):
    r=roop(i,K)
    ans=max(ans,r)
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()))
p=[0]+p
c=[0]+c
m=-1*(10**15)

for i in range(1,n+1):
    roop= 0
    d=["#"]* (n+5)
    t=[-1]* (n+5)
    d[i]= 0
    t[i]= 0
    cur= i
    while True:
        if p[cur] == i:
            t[p[cur]]= t[cur] +1
            d[p[cur]]= d[cur]+ c[p[cur]]
            break
        t[p[cur]]= t[cur] +1
        d[p[cur]]= d[cur]+ c[p[cur]]
        cur= p[cur]
    for j in range(1,n+1):
        if d[j]=="#":
            continue
        m=max(m, ((k-t[j])//t[i])*d[i] +d[j], d[j])

print(m)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(50000)
N,K= [int(v) for v in input().split()]
P = [int(v) - 1 for v in input().split()]
C = [int(v) for v in input().split()]

visited = [True for _ in range(N)]

def dfs(node,total,state,m):
    if visited[node]:
        return total,state,m
    nextM = max(m,total+C[node])
    state.append(C[node])
    total += C[node]
    visited[node] = True
    return dfs(P[node],total,state,nextM)

ans = -float('inf')

def calc(node):
    global visited,ans
    visited = [False for _ in range(N)]
    total,state,ma = dfs(P[node],0,[],-float('inf'))
    ans = max(ma,ans)
    K_ = K
    count = K // len(state)

    tmp = total * count
    for v in state[:K%len(state)]:
        tmp += v
    ans = max(ans,tmp)

    if total > 0:
        tmp = total * (count-1)
        for v in state:
            tmp += v
            ans = max(ans,tmp)






for i in range (N):
    calc(i)

print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
Ps = list(map(int, input().split()))
Ps.insert(0,0)
Cs = list(map(int, input().split()))
Cs.insert(0,0)
Ls = [0] * (n + 1)  # 周期
As = [0] * (n) # 回答候補

# 周期を見つける
for i in range(1,n + 1):
  count = 1
  temp = Ps[i]
  while temp != i:
    temp = Ps[temp]
    count += 1
  Ls[i] = count

# それぞれの最大値を見つける
for i in range(1, n + 1):
  ans = 0
  p = [0] * Ls[i]  #途中経過集
  tempIndex = i
  tempSum = 0
  for j in range(Ls[i]):
    tempIndex = Ps[tempIndex]
    tempSum += Cs[tempIndex]
    p[j] = tempSum
  # print(f'p:{p}')
  # ansを求める
  if p[-1] <= 0:
    ans = max(p[:min(k,Ls[i])])
  else:
    q, r = divmod(k, Ls[i])
    # print(f'q,r,k,Ls[i]:{q}{r}{k}{Ls[i]}')
    start = q * p[-1]
    anss = [0] * r
    anss.insert(0,start)
    tempIndex = i
    tempSum = start
    for z in range(r): #rは高々Ls[i]、つまりn、つまり5 * (10**3)
      tempIndex = Ps[tempIndex]
      tempSum += Cs[tempIndex]
      anss[z + 1] = tempSum
    ans = max(anss)
  As[i-1] = ans
print(max(As))

Submission status: Wrong Answer

Solution code:
def simulate(n, k, p, c):
    score = min(c) * n
    for start in range(n):
        cs = 0
        cm = 0
        m = start
        for i in range(k):
            m = p[m]
            cs += c[m]
            cm = max(cs, cm)
        score = max(cm, score)
    print(score)


def loop(n, k, p, c):
    scores = []
    seen = set()
    for start in range(n):
        m = start
        ls = []
        while m not in seen:
            ls.append(c[m])
            seen.add(m)
            m = p[m]
        seen.add(m)
        if ls:
            scores.append(ls)
    ans = min(c) * n
    for si in scores:
        pc = sum(sij for sij in si if sij > 0)
        nc = sum(sij for sij in si if sij < 0)
        if pc > -nc:
            l = k // len(si)
            m = k % len(si)
            ls = (pc + nc) * l
            ms = sum(si[:m])
            msi = ms
            for i in range(len(si)):
                msi = msi - si[i % len(si)] + si[(i + m) % len(si)]
                ms = max(msi, ms)
            ans = max(ls + ms, ans)
        elif pc > 0:
            ans = max(pc, ans)
        else:
            ans = max(max(si), ans)
    print(ans)


def main():
    n, k = map(int, input().split())
    p = [int(i) - 1 for i in input().split()]
    c = [int(i) for i in input().split()]
    if n > k:
        simulate(n, k, p, c)
    else:
        loop(n, k, p, c)


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()))
Loop = [1] * N
Score = [0] * N
Ans = [0] * N
for i in range(N):
  x = P[i] - 1
  y = C[i]
  while x != i:
    x = P[x] - 1
    y += C[x]
    Loop[i] += 1
  Score[i] = y

for i in range(N):
  a = K // Loop[i]
  b = K % Loop[i]
  x = i
  y = 0
  M = 0
  if b == 0:
    b = Loop[i]
    a = a - 1
  c = max(0, Score[i]) * a
  for j in range(b):
    x = P[x] - 1
    y += C[x]
    if j == 0 or y > M:
      M = y
  Ans[i] = c + M
print(max(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()))
par = [-1 for i in range(n)]
deep = [1 for i in range(n)]
ma = max(c)
def find(x):
    if par[x] < 0:
        return x
    else:
        par[x] = find(par[x])
        return par[x]
def unite(x,y):
    x = find(x)
    y = find(y)
    if x == y:
        return False
    else:
        if deep[x] > deep[y]:
            par[x] += par[y]
            par[y] = x
        elif deep[x] < deep[y]:
            par[y] += par[x]
            par[x] = y
        else:
            par[x] += par[y]
            par[y] = x
            deep[x] += 1
        return True
def same(x,y):
    return find(x) == find(y)
def size(x):
    return -par[find(x)]
for i in range(n):
    unite(i,p[i])
for i in range(n):
    if par[i] >= 0:
        continue
    else:
        t = -par[i]
        if t >= k:
            for j in range(k):
                tmp = 0
                tmp2 = p[i]
                for l in range(j+1):
                    tmp += c[tmp2]
                    tmp2 = p[tmp2]
                tmp3 = p[i]
                ma = max(ma,tmp)
                for l in range(t):
                    tmp += c[tmp2]
                    tmp -= c[tmp3]
                    tmp2 = p[tmp2]
                    tmp3 = p[tmp3]
                    ma = max(ma,tmp)
        else:
            tmpp = p[i]
            tmp7 = 0
            for j in range(t):
                tmp7 += c[tmpp]
                tmpp = p[tmpp]
            if tmp7 <= 0:
                for j in range(t):
                    tmp = 0
                    tmp2 = p[i]
                for l in range(j+1):
                    tmp += c[tmp2]
                    tmp2 = p[tmp2]
                tmp3 = p[i]
                ma = max(ma,tmp)
                for l in range(t):
                    tmp += c[tmp2]
                    tmp -= c[tmp3]
                    tmp2 = p[tmp2]
                    tmp3 = p[tmp3]
                    ma = max(ma,tmp)
            else:
                g = k//t
                g2 = k//t - 1
                ma2 = 0
                ma3 = 0
                for j in range(k % t):
                    tmp = 0
                    tmp2 = p[i]
                    for l in range(j+1):
                        tmp += c[tmp2]
                        tmp2 = p[tmp2]
                    tmp3 = p[i]
                    ma2 = max(ma2,tmp)
                    for l in range(t):
                        tmp += c[tmp2]
                        tmp -= c[tmp3]
                        tmp2 = p[tmp2]
                        tmp3 = p[tmp3]
                        ma2 = max(ma2,tmp)
                ma2 += tmp7 * g
                for j in range(t):
                    tmp = 0
                    tmp2 = p[i]
                    for l in range(j+1):
                        tmp += c[tmp2]
                        tmp2 = p[tmp2]
                    tmp3 = p[i]
                    ma3 = max(ma3,tmp)
                    for l in range(t):
                        tmp += c[tmp2]
                        tmp -= c[tmp3]
                        tmp2 = p[tmp2]
                        tmp3 = p[tmp3]
                        ma3 = max(ma3,tmp)
                ma3 += tmp7 * g2
                ma = max(max(ma,ma2),ma3)
print(ma)

Submission status: Wrong Answer

Solution code:
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7


n,k=mdata()
p=mdata()
c=mdata()
l=[]
vis=[0]*n
ans=0
flag=0
for i in range(n):
    vis=[0]*n
    q=[i]
    c1=[c[i]]
    t=0
    while True:
        a=q[-1]
        vis[a]=1
        if vis[p[a]-1]==1:
            t=p[a]-1
            break
        else:
            q.append(p[a]-1)
            c1.append(c[p[a]-1])
    m=0
    m1=-c1[0]
    for j in range(len(q)):
        if q[j]==t or j>k:
            break
        m1+=c1[j]
        if m1 >= 0:
            flag1 += 1
        m=max(m1,m)
    t1=m1
    flag1=0
    if j<=k:
        for j1 in range(j,min(len(q),k)):
            m1 += c1[j1]
            m = max(m1, m)
            if m1>=0:
                flag1+=1
        s=sum(c1[j:])
        t1+=((k+1-j)//(len(q)-j))*s
        if t1 >= 0:
            flag1 += 1
        m1=0
        m2=0
        for j1 in range(j,j+(k+1-j)%(len(q)-j)):
            m1+=c1[j1]
            m2=max(m1,m2)
        t1+=m2
        if m1 >= 0:
            flag1 += 1
        m=max(m,t1)
        flag=max(flag,flag1)
    ans=max(ans,m)
if flag<2:
    ans=-INF
    for i in range(n):
        ans=max(ans,c[p[i]-1])
out(ans)

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    N, K = map(int, input().split())
    P = tuple(map(lambda x: int(x) - 1, input().split()))
    C = tuple(map(int, input().split()))
    ans = -10**18

    for i in range(N):
        k = K
        D = [[0, 0] for i in range(N)]
        x = i
        X, Y = 0, 0
        count = 0
        score = 0
        for j in range(K):
            if D[P[x]][0] == 0:
                score += C[P[x]]
                D[P[x]][0] = score
                D[P[x]][1] = count
                x = P[x]
                count += 1
            else:
                X = D[P[x]][0] - C[P[x]]
                score -= X
                L = (count - D[P[x]][1])
                k -= D[P[x]][1]
                score2 = score + X
                score *= k // L
                l = K % L
                score += X
                ans = max(ans, score)
                for h in range(N):
                    if D[h][1] <= l + D[P[x]][1] - 1:
                        ans = max(ans, score + D[h][0] - X)
                    ans = max(ans, score2 + D[h][0] - X)
                break
            if score > ans:
                ans = score
    print(ans)


main()

Submission status: Wrong Answer

Solution code:
nk=input("").split(" ")
n=int(nk[0])
k=int(nk[1])
lisp=input("").split(" ")
lisc=input("").split(" ")
p=[]
c=[]
plis=[]
for i in range(n):
    p+=[int(lisp[i])-1]
    c+=[int(lisc[i])]
    plis+=[1]
cycle=[]
cyp=[]
cyc=[]


for i in plis:
    
    
        np=p[i]
        cys=c[i]
        
        cyct=[c[i]]
        while(np!=i):
            
            cys+=c[np]
            
            cyct+=[cys]
            np=p[np]
        cycle+=[cys]
        
        cyc+=[cyct]
if(max(cycle)<=0):
    m=max(cyc[0])
    
    for i in cyc:
        if(m<max(i)):
            m=max(i)
    print(m)
elif(k>2*n):
    m=[cycle[0],len(cyc[0])]
    t=[0]
    
    for i in range(n):
        if(m[0]*len(cyc[i])<cycle[i]*m[1]):
            m=[cycle[i],len(cyc[i])]
            t=[i]
        elif(m[0]*len(cyc[i])==cycle[i]*m[1]):
            t+=[i]
    lll=len(cyc[t[0]])
    for i in t:
        if(lll<len(cyc[i])):
            lll=len(cyc[i])
    syou=(k-1)//lll
    amari=(k-1)%lll
    ten=syou*cycle[i]
    tama=0
    
    for i in t:
        syo=amari//len(cyc[i])
        if(tama<syo*cycle[i]+cyc[i][amari%len(cyc[i])]):
            tama=syo*cycle[i]+cyc[i][amari%len(cyc[i])]
            
    print(ten+tama)
else:
    t=0
    for i in range(n):
        cc=c[i]
        ccc=[cc]
        np=p[i]
        
        for kws in range(k):
                cc+=c[np]
                
                np=p[np]
                ccc+=[cc]
        
        if(t<max(ccc)):
            t=max(ccc)
    print(t)

Submission status: Wrong Answer

Solution code:
import sys
from itertools import accumulate

read = sys.stdin.read
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7


def main():
    N, K = map(int, readline().split())
    P = list(map(int, readline().split()))
    C = list(map(int, readline().split()))
    groups = []
    used = [False]*N
    for i in range(N):
        if used[i]:
            continue
        else:
            tmp = [i]
            used[i] = True
            while True:
                next = P[tmp[-1]]-1
                if used[next]:
                    break
                else:
                    used[next]=True
                    tmp.append(next)
            groups.append(tmp)

    ans = -10**10
    for group in groups:
        score = 0
        L = len(group)
        points = []
        for i in group:
            points.append(C[i])
        if sum(points)>=0:
            if K>=L:
                score += sum(points)*(K//L)
        acc = [0] + list(accumulate(points+points))
        a = -10**10
        for k in range(1,(K-1)%L+2):
            for i in range(L):
                print(acc[i+k]-acc[i])
                a = max(a, acc[i+k]-acc[i])
        score += a
        ans = max(ans, score)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 15 21:20:49 2020

@author: NEC-PCuser
"""

N, K = map(int, input().split())

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

X = [0] * N
c_li = []
position = 0 
for i in range(len(P)):
	if X[i] == 1:
		continue
	position = i
	li = []
	for j in range(len(P)):
		X[position] = 1
		li.append(C[position])
		position = P[position] - 1
		if position == i:
			c_li.append(li)
			break
ans = -1000000001
for x_li in c_li:
	q = K % len(x_li)
	if q == 0:
		q = len(x_li)
	r = K // len(x_li)
	max_score = -1000000001
	for i in range(0, len(x_li)):
		k = i
		score = 0
		for j in range(q):
			score += x_li[k]
			if max_score < score:
				max_score = score
			k += 1
			if len(x_li) == k:
				k = 0
	sum_c = sum(x_li)
	if (sum_c > 0):
		if ans < max_score + r * sum_c:
			ans = max_score + r * sum_c
	else:
		if ans < max_score:
			ans = max_score
		
print(ans)

Submission status: Wrong Answer

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

ans=C[P[1]]+0
for i in range(1, N+1):
  ima=i+0
  kako=[[None, None] for _ in range(N+1)]
  kako[i]=[0, 0]
  for count in range(1, K+1):
    if kako[P[ima]]!=[None, None]:
      if kako[P[ima]][1]<kako[ima][1]+C[P[ima]]:
        atonanshu=(K-count)//(count-kako[P[ima]][0])
        atonanho=(K-count)%(count-kako[P[ima]][0])
        agatta=kako[ima][1]+C[P[ima]]-kako[P[ima]][1]
        
        kako[P[ima]]=[count+atonanshu*(count-kako[P[ima]][0]), kako[ima][1]+C[P[ima]]+agatta*atonanshu]
        ima=P[ima]+0
        for _ in range(atonanho):
          kako[P[ima]]=[count, kako[ima][1]+C[P[ima]]]
          ima=P[ima]+0
      break
    else:
      kako[P[ima]]=[count, kako[ima][1]+C[P[ima]]]
      ima=P[ima]+0
      
  if kako[i][0]==0:
    kako[i]=[None, None]
  ans=max(ans, max([k[1] for k in kako if k[1] is not None]))
  
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = list(map(int, input().split()))
p = [int(i) - 1 for i in input().split()]
c = [int(i) for i in input().split()]
import copy
p_list = [[0 for _ in range(n)] for _ in range(n)]
position = [[-1 for _ in range(n)] for _ in range(n)]
t = (k % n) - 1
tmp = copy.deepcopy(c)
for i in range(n):
    p_list[0][i] += c[p[i]]
    position[0][i] = p[i]
for i in range(1, n):
    for j in range(n):
        p_list[i][j] = p_list[i - 1][j] + c[p[position[i - 1][j]]]
        position[i][j] = p[position[i - 1][j]]
        if i <= t:
            tmp[j] = max(tmp[j], p_list[i][j])
ans = max(c)
for i in range(n):
    v = p_list[-1][i] * (k // n)
    if k % n > 0:
        v += tmp[i]
    ans = max(v, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
n,k=map(int,input().split())
p=[i-1 for i in list(map(int,input().split()))]
c=list(map(int,input().split()))
r1,r2=deque(),deque()
r3=0
for i in p:
  r1=[i]
  r2=[]
  for j in range(k):
    r2.append(c[r1[-1]])
    r1.append(p[r1[-1]])
    r3=max(r3,sum(r2))
print(r3)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
ListJ = list(map(int, input().split()))
ListP = list(map(int, input().split()))
INF = -10000000000
List = [INF]*N
flag = True
point = 0
pointMax = -10000000000
mid = 0
for i in range(N):
  flag = True
  point = 0
  mid = 0
  List = [INF]*N
  k = i
  while flag:
    if List[k] != INF:
      flag = False
    else:
      mid +=  ListP[k]
      List[k] = mid
      k = ListJ[k]-1
  if mid >0:
    n = List.count(INF)
    n = N-n
    period = N//n
    point = period*mid
    for i in range(K-period*n):
      mid +=  ListP[k]
      k = ListJ[k]-1
      point = max(point,mid)
    pointMax = max(point,pointMax)
  else:
    num_list = list(map(int, List))
    point = max(num_list)
    pointMax = max(pointMax,point)
print(pointMax)