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: Time Limit Exceeded

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)]
def RI(a=1,b=10):return random.randint(a,b)
def Rtest(T):
    case,err=0,0
    for i in range(T):
        inp=INP()
        a1,ls=naive(*inp)
        a2=solve(*inp)
        if a1!=a2:
            print((a1,a2),inp)
            err+=1
        case+=1
    print('Tested',case,'case with',err,'errors')
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in R(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**9)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()


show_flg=False
show_flg=True

ans=0

n,k=LI()
p=LI_()
c=LI()

rp=[-1]*n
pp=[-1]*n
def roop(y):
    pt=0
    if rp[y]!=-1:
        return rp[y],pp[y]
    x=y
    for i in range(n):
        x=p[x]
        pt+=c[i]
        if x==y:
            r=i+1
            break
    rp[y]=r
    
    x=y
    for i in range(r+1):
        rp[x]=r
        pp[x]=pt
        x=p[x]
        
    return r,pt

def tr(x,t):
    pt=0
    rt=-inf
    for i in range(t):
        x=p[x]
        pt+=c[x]
        rt=max(rt,pt)
    return rt



ans=-inf
for i in range(n):
    r,ppx=roop(i)
    if k<=n:
        tmp=tr(i,k)
    else:
        tmp0=tr(i,k)    
        tmp1=(k//r)*ppx+tr(i,k%r)
        tmp2=max(0,(k//r)-1)*ppx+tr(i,n)
        tmp=max(tmp0,tmp1,tmp2)
    ans=max(tmp,ans)
    #show(i,(r,pp),tr(i,n),(k//r),tmp)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
a = list(input().split(" "))
masu = int(a[0])
idou = int(a[1])

b = list(input().split(" "))
c = list(input().split(" "))

for i in range(masu):
    b[i] = int(b[i])
    c[i] = int(c[i])
b.insert(0,0)
c.insert(0,0)

m = -10000000000
for i in range(1,masu+1):
    p = 0
    d = b[i]
    for j in range(idou):
        p += c[d]
        d = b[d]
        if m < p:
            m = p

print(m)

Submission status: Time Limit Exceeded

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

x = [0] * n
t = list(range(1,n+1))

for j in range(k):
    for i in range(n):
        x[i] += c[t[i]-1]
        t[i] = p[t[i]-1]
        ans = max(ans, x[i])

print(ans)

Submission status: Time Limit Exceeded

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

ans=min(C)

for i in range(N):
  sum_num=0
  cnt=0
  index=i
  S=[0]*N
  for j in range(K):
    cnt+=1
    index=P[index]-1
    sum_num+=C[index]
    S[j]=sum_num
    ans=max(ans,sum_num)
    if cnt>1 and i==index:
      ans=max(ans,sum_num*(K//cnt)+S[K%cnt-1])
      break
  else:
    ans=max(ans,sum_num)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    n, k = map(int,input().split())
    p = list(map(int,input().split()))
    c = list(map(int,input().split()))
    l = []
    for i in range(n):
        point = 0
        ind = i
        for _ in range(k):
            ind = p[ind-1]
            point += c[ind - 1]
            l.append(point)
    print(max(l))
resolve()

Submission status: Time Limit Exceeded

Solution code:
n, k = [int(_) for _ in input().split()]
p = [int(_)-1 for _ in input().split()]
c = [int(_) for _ in input().split()]
ans = -10**9 - 1
for i in range(n):
    idx = i
    s = [-10**9 - 1 for i in range(n)]
    s[0] = c[idx]
    ishuu = 0
    cu = 1
    for cu in range(1, n+1):
        idx = p[idx]
        ishuu += 1
        if idx == i:
            break
        s[cu] = s[cu-1]+c[idx]

        # cu = max(s)
    # print(s)
    if k >= ishuu:
        ans = max(ans, (k//ishuu-1)*s[cu-1] + max(s), max(s))

        if (k % ishuu) != 0:
            ans = max(ans, (k//ishuu)*s[cu-1]+max(s[: k % ishuu]))
        else:
            ans = max(ans, (k//ishuu)*s[cu-1])
    else:
        ans = max(ans, max(s[:k]))
    # print(ans, s)
    # print(s[-1], s, (k//ishuu-1)*s[-1] + max(s), ans),
    #       (k//ishuu)*max(s[-1], 0)+max(s[: k % ishuu]))

print(ans)

Submission status: Time Limit Exceeded

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

max_score = -1000000000
for i in range(n):
    score = 0
    start = p[i]-1
    now = start
    for _ in range(k):
        score += c[now]
        max_score = max(max_score,score)
        now = p[now]-1
        if now == start:
            if score < 0:
                break
print(max_score)

Submission status: Time Limit Exceeded

Solution code:
n,k=(map(int,input().split()))
p=list(map(int,input().split()))
c=list(map(int,input().split()))
cnt=list(range(n))
ans=-(10**10)
for i in range(n):
    num=[0]
    num11=[]
    num2=p[cnt[0]]-1
    num3=cnt[0]
    cnt.remove(cnt[0])
    for j in range(n+1):
        cnt10=c[num2]
        num.append(num[-1]+cnt10)
        num11.append(cnt10)
        if num2==num3:
            break
        cnt.remove(num2)
        num2=p[num2]-1
    lnum=len(num)-1
    for j in range(lnum):
        num.append(num[-1]+num11[j])
    if num[-1]<0 or k<lnum:
        ans2=-(10**10)
        for j in range(lnum):
            cnt2=num[j]
            num10=0
            for l in range(min(lnum,k)):
                ans2=max(ans2,num[j+l+1]-cnt2)
        ans=max(ans,ans2)
    else:
        ans3=-(10**10)
        ans4=0
        ans5=-(10**10)
        for j in range(lnum):
            cnt2=num[j]
            num10=0
            num14=k%lnum
            for l in range(lnum):
                ans3=max(ans3,num[j+l+1]-cnt2)
                if num14>l:
                    ans5=max(ans5,num[j+l+1]-cnt2)
        ans6=k//lnum
        ans=max(ans,(ans6*num[lnum])+ans5,((ans6-1)*num[lnum])+ans3)
    if len(cnt)==0:
        break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
p = [int(pn) for pn in input().split()]
c = [int(cn) for cn in input().split()]
scores = []
cache_append = scores.append
for i in range(n):
  genzai = p[i] - 1
  score = c[genzai]
  cache_append(score)
  for _ in range(k-1):
    genzai = p[genzai] - 1
    score += c[genzai]
    cache_append(score)
print(max(scores))

Submission status: Time Limit Exceeded

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

s_max = max(C)
for n in range(N):
    s = 0
    p = n + 1
    for k in range(K):

        p = P[p-1]
        s += C[p-1]

        if s > s_max:
            s_max = s


print(s_max)

Submission status: Time Limit Exceeded

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)

sumC = sum(C) 

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

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

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

Submission status: Time Limit Exceeded

Solution code:
n, k = [int(_) for _ in input().split()]
p = [int(_)-1 for _ in input().split()]
c = [int(_) for _ in input().split()]
ans = -10**9 - 1
for i in range(n):
    idx = i
    s = [-10**9 - 1 for i in range(n)]
    s[0] = c[idx]
    ishuu = 0
    cu = 1
    while 1:
        idx = p[idx]
        ishuu += 1
        if idx == i:
            break
        s[cu] = s[cu-1]+c[idx]
        cu += 1
        # cu = max(s)
    # print(s)
    if k >= ishuu:
        ans = max(ans, (k//ishuu-1)*s[cu-1] + max(s), max(s))

        if (k % ishuu) != 0:
            ans = max(ans, (k//ishuu)*s[cu-1]+max(s[: k % ishuu]))
        else:
            ans = max(ans, (k//ishuu)*s[cu-1])
    else:
        ans = max(ans, max(s[:k]))
    # print(ans, s)
    # print(s[-1], s, (k//ishuu-1)*s[-1] + max(s), ans),
    #       (k//ishuu)*max(s[-1], 0)+max(s[: k % ishuu]))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
scoresum=[]
for i in range(n):
    score=0
    scorelist=[0]
    placesum=[i]
    place=p[i]-1
    for j in range(n):
        if placesum.count(place)==0:
            placesum.append(place)
            score+=c[place]
            scorelist.append(score)
            place=p[place]-1
        else:
            pro=placesum.index(place)
            placesum.append(place)
            score+=c[place]
            scorelist.append(score)
            loop=j+1-pro
            break
    if j+1>=k:
        scoresum.append(max(scorelist[1:k+1]))
    else:
        if scorelist[pro]>=scorelist[j+1]:
            scoresum.append(max(scorelist[1:]))
        else:
            aa=(k-pro)//loop
            loopscore=scorelist[j+1]-scorelist[pro]
            if (k-pro)%loop!=0:
                scoresum.append(max(max(scorelist[pro:(k-pro)%loop+pro+1])+loopscore,max(scorelist[(k-pro)%loop+pro+1:]))+(aa-1)*loopscore)
            else:
                scoresum.append(max(scorelist[pro:])+(aa-1)*loopscore)
print(max(scoresum))

Submission status: Time Limit Exceeded

Solution code:
n, k = list(map(int, input().split()))
p = list(map(int, input().split()))
c = list(map(int, input().split()))
best_score = -6000 * 10**9

for i in range(n):
  appeared = set()
  lb_score = -6000 * 10**9
  score = 0
  now = i
  appeared.add(now)
  flag = 0
  for j in range(1, k+1):
    now = p[now] - 1 # index 化のために -1
    score += c[now]
    if score > lb_score:
      lb_score = score
    if now in appeared:
      score *= (k // j)
      if score > lb_score:
        lb_score = score
      extra = k % j
      flag = 1
      break
    appeared.add(now)
  if flag == 1:
    for _ in range(extra):
      now = p[now] - 1 # index 化のために -1
      score += c[now]
      if score > lb_score:
        lb_score = score
  if lb_score > best_score:
    best_score = lb_score

print(best_score)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
si = sys.stdin.readline


def main():
    [n, num] = [int(e) for e in si().split()]
    pl = [int(e) for e in si().split()]
    cl = [int(e) for e in si().split()]

    M = -1000000000*5000-1
    for i in range(n):
        flag, k, idx, m, cycle, cstack, cv, cn = False, num, i, 0, set(), deque(), 0, 0
        while k:
            k -= 1
            idx = pl[idx]-1
            if not flag and idx in cycle:
                flag = True
                end = cstack.pop()
                while end != idx:
                    cv += cl[end]
                    cn += 1
                    end = cstack.pop()
                cv += cl[end]
                cn += 1
                rest = k//cn
                if rest:
                    k -= cn*rest
                    m += cv*rest
            if idx not in cycle:
                cycle.add(idx)
                cstack.append(idx)
            m += cl[idx]
            M = max(M, m)
    print(M)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N,K = list(map(int,input().split()))
P = list(map(int,input().split()))
C = list(map(int,input().split()))
##################################################################
max_point = -10000000000000
for i in range(N):
  point = 0
  now = i
  for j in range(K):
    next_place = P[now]-1
    point += C[next_place]
    max_point = max(point,max_point)
    now = next_place

print(max_point)

Submission status: Time Limit Exceeded

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

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

c = C[P[0]-1]

for i in range(n):
    t = 0
    
    L = []
    S = set()
    for j in range(k):
        if j == 0:
            now = P[i]-1
        else:
            now = P[now]-1

        t += C[now]
        if c < t:
            c = t
            
        #print(i,j,c)
    #print(L)
print(c)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

n, k = map(int, input().split())
p = [0] + list(map(int, input().split()))
c = [0] + list(map(int, input().split()))

dp = {}
for i in range(1, n + 1):
    dp[(i, 0)] = 0
    dp[(i, 1)] = c[p[i]]

def score(i, k, route):
    if (i, k) in dp:
        return dp[(i, k)]
    else:
        if i in route and k >= len(route):
            tmp_ans = 0
            for r in route:
                tmp_ans += dp[(r, 1)]
            return (tmp_ans * (k // len(route))) + score(p[i], k % len(route), route)
        else:
            route = route.copy()
            route.add(i)
            return c[p[i]] + score(p[i], k - 1, route)

ans = None
for i in range(1, n + 1):
    for j in range(1, k + 1):
        tmp_ans = score(i, j, set())
        if ans == None:
            ans = tmp_ans
        else:
            ans = max(ans, tmp_ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int,input().split())
P = list(map(int,input().split()))
P = [p-1 for p in P]
C = list(map(int,input().split()))

# score[i][j] = i-th score, position when start from j
score = [[(-(10**9) if i > 0 else 0, j) for j in range(N)] for i in range(N+1)]
T = [0 for i in range(N)]
for i in range(1, N+1):
	for j in range(N):
		if T[j] > 0:
			continue
		(s,p) = score[i-1][j]
		next_p = P[p]
		score[i][j] = (s + C[next_p], next_p)
		if j == next_p:
			T[j] = i

if K <= N:
	print(max([max([s[i][0] for i in range(N)]) for s in score[1:K+1]]))
	exit()

ans = -(10 ** 9)
M = [[-(10**13) for j in range(N)] for i in range(N+1)]
for i in range(1, N+1):
	for j in range(N):
		M[i][j] = max(M[i-1][j], score[i][j][0])
for i in range(N):
	t = T[i]
	S = score[t][i][0]
	if S > 0:
		base = S * (K // t)
		r = K % t
		ad = max(0, M[r][i])
		ans = max(ans, base + ad)
	else:
		ans = max(ans, M[N][i])
print(ans)

Submission status: Time Limit Exceeded

Solution code:

N, K = list(map(int, input().split()))
Ps = list(map(int, input().split()))
Cs = list(map(int, input().split()))
S = Cs.copy()

max_score = -100000000000000000
for i in range(N):
    tmp = 0
    c = Ps[i]
    for j in range(K):
        tmp += Cs[c-1]
        c = Ps[c-1]
        if max_score < tmp:
            max_score = tmp
print(max_score)

Submission status: Time Limit Exceeded

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

max_score = -10**10
for i in range(N):
  score = 0
  p = P[i]
  for k in range(K):
    score += C[p - 1]
    p = P[p - 1]
    if score > max_score:
      max_score = score
print(max_score)

Submission status: Time Limit Exceeded

Solution code:
n,k = (int(x) for x in input().split())

p = input().split(' ')
c = input().split(' ')

point = []


for j in range(n):
    next = int(p[j])-1
    temp = 0
    for i in range(k):
        temp += int(c[next])
        point.append(temp)
        next = int(p[next])-1

print(max(point))

Submission status: Time Limit Exceeded

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

for i in range(N):
  P[i] -= 1

ans = max(C)
S = set(range(N))
while S:
  scores = []
  x = min(S)
  while x in S:
    S.remove(x)
    scores.append(C[x])
    x = P[x]
  l = len(scores)
  if K <= l:
    for i in range(l):
      if scores[i] <= 0:
        continue
      ss = 0
      for k in range(K):
        ss += scores[(i+k)%l]
        ans = max(ans, ss)
  else:
    t = sum(scores)
    t = t * (K // l - 1) if t > 0 else 0
    for i in range(l):
      if scores[i] <= 0:
        continue
      ss = t
      for k in range(l + (K%l)):
        ss += scores[(i+k)%l]
        ans = max(ans, ss)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
l = list(map(int,input().split()))
n = l[0]
k = l[1]
p = list(map(int,input().split()))
c = list(map(int,input().split()))

dp = [[0] * n for i in range(k)]
for i in range(n):
  dp[0][i] = c[p[i]-1]

for j in range(1,k):
  for i in range(n):
    dp[j][i] = dp[0][i] + dp[j-1][p[i]-1]

ans = -10**9
for j in range(k):
  m = max(dp[j])
  ans = max(ans,m)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
def main():    
    input = sys.stdin.readline
    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    l = []
    for i in range(n):
        cur = i
        l2 = []
        l3 = []
        score = 0
        cnt = 0
        while True:
            if p[i] - 1 in l2:
                score += c[p[i] - 1]
                l3.append(score)
                break
            l2.append(i)
            score += c[p[i] - 1]
            l3.append(score)
            i = p[i] - 1
            cnt += 1
        l.append([l3, cnt + 1])
    A = []
    for i in range(n):
        x, y = l[i][0], l[i][1]
        ans = 0
        if x[-1] < 0:
            if k >= y:
                ans = max(x)
            else:
                if k % y == 0:
                    pass
                else:
                    ans = max(x[:k % y])
        else:
            ans = x[-1] * (k // y)
            if k % y == 0:
                pass
            else:
                ans += max(x[:k % y])
        A.append(ans)
    print(max(A))
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
n, k = map(int, input().split())
p_list = list(map(int, input().split()))
c_list = list(map(int, input().split()))
check_dict = {}
loop_list = []
flag = 0
for i in range(n):
    if i in check_dict:
        continue
    next_no = i
    score_list = []
    check_dict[next_no] = 1
    while True:
        score_list.append(c_list[next_no])
        if flag == 0:
            if c_list[next_no] > 0:
                flag = 1
        next_no = p_list[next_no] - 1
        if next_no in check_dict:
            break
        else:
            check_dict[next_no] = 1
    loop_list.append(score_list)
if flag == 0:
    print(max(c_list))
else:
    max_score = 0
    for score_list in loop_list:
        if sum(score_list) <= 0 or len(score_list) <= k:
            for start in range(len(score_list)):
                score = 0
                if score_list[start] <= 0:
                    continue
                for i in range(start, start + k):
                    temp_i = i % len(score_list)
                    score += score_list[temp_i]
                    if score > max_score:
                        max_score = score
        else:
            t = k // len(score_list)
            sum_score = sum(score_list) * t
            t = k - t * len(score_list)
            for start in range(len(score_list)):
                score = 0
                if score_list[start] <= 0:
                    continue
                for i in range(start, start + t):
                    temp_i = i % len(score_list)
                    score += score_list[temp_i]
                    if score + sum_score > max_score:
                        max_score = score + sum_score
    print(max_score)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
def main():
  input = sys.stdin.readline
  n, k = map(int , input().split())
  p_list = np.array(list(map(int, input().split())))
  c_list = np.array(list(map(int, input().split())))
  
  dp = [[float('-inf')]*n for _ in range(k+1)]
  dp[0] = [0]*n
  for i in range(k):
    for j in range(n):
      if i==0:
        dp[i+1][p_list[j]-1] = dp[i][j]+c_list[j]
      else:
        dp[i+1][p_list[j]-1] = max(dp[i][p_list[j]-1], dp[i][j]+c_list[j])
  print(max(dp[-1]))

if (__name__=='__main__'):
  main()

Submission status: Time Limit Exceeded

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

for i in range(N):
  for j in range(K+1):
    if j==0:
      total = 0
      locate = P[i]
    else:
      total += C[locate-1]
      locate = P[locate-1]
      if i==0:
        ans = total
      elif ans < total:
        ans = total
    
print(ans)

Submission status: Time Limit Exceeded

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
        now=j
        pscore2=0
        pscore_max2=0
        for y in range(s[j][1]):
            now=(p[now]-1)
            pscore2+=c[now]
            pscore_max2=max(pscore_max2,pscore2)
        score2+=pscore_max2
        score_max=max(score1,score2)
    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: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
N_max_list = [0] * N

for i in range(N):
    play = 0
    place = i
    score = 0
    memory = []
    local_max = -float("inf")
    lm_list = []
    while True:
        memory.append(place)
        place = P[place] - 1
        score += C[place]
        local_max = max(local_max, score)
        lm_list.append(local_max)
        play += 1
        if place in memory:
            if score > 0:
                if K % play == 0:
                    N_max_list[i] = score * (K // play)
                else:
                    N_max_list[i] = score * (K // play) + max(lm_list[:K % play])
            else:
                N_max_list[i] = local_max
            break
        if play == K:
            N_max_list[i] = local_max
            break
print(max(N_max_list))

Submission status: Time Limit Exceeded

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

max_score = -1000000000
for i in range(n):
    score = 0
    now = p[i]-1
    for _ in range(k):
        score += c[now]
        max_score = max(max_score,score)
        now = p[now]-1
print(max_score)

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
P = [x-1 for x in P]
X = C[0]

for i in range(N):
  k = i
  S = 0
  SS = []
  for j in range(K):
    S += C[P[k]]
    SS.append(S)
    k = P[k]
  X = max(X,max(SS))
print(X)

Submission status: Time Limit Exceeded

Solution code:
from copy import copy
n, k = map(int, input().split())
p = list(map(int,input().split()))
c = list(map(int, input().split()))
di = {}
for i in range(n):
    di[i+1] = False
l = 1
cc = 0
per = [] # ループの順番
while cc < n:
    tmp = []
    while True:
        if di[l]:
            break
        else:
            tmp.append(l)
            di[l] = True
            cc += 1
            l = p[l-1]
    per.append(tmp)
    for i in range(n):
        if not di[i+1]:
            l = p[i]
#print(per)
dd = {} # 何個目のループに属するか
for i in range(n):
    dd[i+1] = 0
for i in range(len(per)):
    for j in per[i]:
        dd[j] = i
#print(dd)
su = [] # ループ１週の和
for i in range(len(per)):
    tmp = 0
    for j in per[i]:
        tmp += c[j-1]
    su.append(tmp)
#print(su)
s2 = [] # ループ１週何個か
for i in range(len(per)):
    s2.append(len(per[i]))
#print(s2)
ans = -1*(10**10)
#d2 = {} # per[dd]の中でなんばんめにあるか(0インデックス)
#for i in range(len(per)):
#    for j in range(len(per[i])):
#        d2[per[i][j]] = j
#print(d2)
aa = []
for i in range(n):
    loop = dd[i+1]
    w = i+1
    kk = copy(k)
    if k < s2[loop]:
        tmp = 0
        m = -10**9
        for j in range(k):
            w = p[w-1]
            tmp += c[w-1]
            aa.append(tmp)
    else:
        if su[loop] <= 0:
            tmp = 0
            m = -10**9
            for j in range(k):
                w = p[w-1]
                tmp += c[w-1]
                aa.append(tmp)
        else:
            m_loop = kk // (s2[loop])
            m_loop -= 1
            kk -= m_loop * s2[loop]
            tmp = su[loop]*m_loop
            m = -10**9
            for j in range(kk):
                w = p[w-1]
                tmp += c[w-1]
                if c[w-1] <= 0:
                    continue
                aa.append(tmp)
print(max(aa))

Submission status: Time Limit Exceeded

Solution code:
#import
#import math
#import numpy as np
#= int(input())
#= input()
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

for i in range(N):
    P[i] -= 1

ans = -10**30

for n in range(N):
    tmax = -10**30
    t = 0
    c = 0
    ni = n
    goto = True
    while True:
        t += C[ni]
        c += 1
        ni = P[ni]
        tmax = max(t, tmax)
        if n == ni:
            break
        if c == K:
            ans = max(ans, tmax)
            goto = False
            break

    if goto:
        t *= (K // c)
        tt = t
        ni = n
        for i in range(K % c):
            t += C[ni]
            c += 1
            ni = P[ni]
            tt = max(t, tt)

        ans = max(ans, tmax, tt)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

N, K = [int(x) for x in input().strip().split(" ")]
P = [int(x) - 1 for x in input().strip().split(" ")]
C = [int(x) for x in input().strip().split(" ")]


def calc_score(begin, cnt):
    score = 0
    pos = begin
    for _ in range(cnt):
        next_pos = P[pos]
        score += C[next_pos]
        pos = next_pos
    return score

scores = []
for p in range(N):
    for c in range(1, K + 1):
        scores.append(calc_score(p, c))
print(max(scores))

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int, input().split())
Ps=list(map(int, input().split()))
Cs=list(map(int, input().split()))
  
vl=[]
for i in range(1,N+1):
  for k in range(1,K+1):
    m=i
    v=0
    for x in range(k):
      v += Cs[Ps[m-1]-1]
      m=Ps[m-1]
    vl.append(v)
    
print(max(vl))