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: Runtime Error

Solution code:
#include <bits/stdc++.h>

using namespace std;

#define eb emplace_back
#define ii pair<int, int>
#define OK (cerr << "OK" << endl)
#define debug(x) cerr << #x " = " << (x) << endl
#define ff first
#define ss second
#define int long long
#define tt tuple<int, int, int>
#define all(x) x.begin(), x.end()
#define vvi vector<vector<int>>
#define vvii vector<vector<pair<int, int>>>
#define Mat(n, m, v) vector<vector<int>>(n, vector<int>(m, v))
#define endl '\n'

constexpr int INF = 2e18;
constexpr int MOD = 1e9 + 7;
constexpr int MAXN = 5e3 + 3;

vector<int> cur;
vector<int> nxt(MAXN);
vector<int> v(MAXN);
vector<int> vis(MAXN);
vector<int> cycle(MAXN);
vector<int> vt;

void dfs(int u) {
  cur.eb(v[nxt[u]]);
  vt.eb(u);
  vis[u] = true;
  if (!vis[nxt[u]])
    dfs(nxt[u]);
  else
    cycle[u] = cycle[nxt[u]] = true;
}

// #define MULTIPLE_TEST_CASES
void solve() {
  int n;
  int k;
  cin >> n;
  cin >> k;

  for (int i = 1; i <= n; ++i) {
    cin >> nxt[i];
  }

  for (int i = 1; i <= n; ++i) {
    cin >> v[i];
  }

  int ans = -INF;
  for (int i = 1; i <= n; ++i) {
    int kk = k;
    vis.assign(n + 1, 0);
    cycle.assign(n + 1, 0);
    cur.clear();
    vt.clear();
    dfs(i);
    reverse(all(cur));
    reverse(all(vt));
    int vans = 0;
    while (kk > 0 && !cycle[vt.back()]) {
      vans += cur.back();
      --kk;
      cur.pop_back();
      vt.pop_back();
    }
    reverse(all(cur));
    int val = accumulate(all(cur), 0ll);
    // debug(val);
    if (val > 0) {
      vans += (kk / (int)cur.size()) * val;
    } else if (kk > (int)cur.size()) {
      for (int i = 0; i < min(kk, (int)cur.size()); ++i) {
        vans += cur[i];
        ans = max(ans, vans);
      }
      continue;
    }
    kk %= (int)cur.size();
    ans = max(ans, vans);
    for (int i = 0; i < kk; ++i) {
      vans += cur[i];
      ans = max(ans, vans);
    }
  }

  cout << ans << endl;
}

signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);

  int t = 1;
#ifdef MULTIPLE_TEST_CASES
  cin >> t;
#endif
  while (t--)
    solve();
}

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (int)(n); i++)
using namespace std;
#define int long long

const int INF = LONG_LONG_MAX;

signed main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n,k;
  cin >> n >> k;

  vector<int> p(n + 1);
  vector<int> c(n + 1);

  for (int i = 1; i <= n; i++) cin >> p[i];
  for (int i = 1; i <= n; i++) cin >> c[i];

  vector<vector<int>> route;

  vector<int> visited(n + 1, 0);
  for (int i = 1; i <= n; i++) {
    if(visited[p[i]]) continue;

    vector<int> path;
    path.push_back(c[i]);
    visited[p[i]] = 1;

    int cur = p[i];
    while(true) {
      if(visited[p[cur]]) break;
      visited[p[cur]] = 1;
      path.push_back(c[cur]);
      cur = p[cur];
    }
    route.push_back(path);
  }

  int answer = -INF;

  for (vector<int> cycle : route) {
    int m = (int)cycle.size();
    for (int start = 0; start < m; start++) {
      int cycle_sum = 0;

      for (int i = 0; i < min(k,m); i++) {
        cycle_sum += cycle[(start + i) % m];
        answer = max(answer, cycle_sum);
      }

      if(k <= m || cycle_sum < 0) continue;

      int tmp = (k/m - 1) * cycle_sum;
      int cnt = k%m + m;

      answer = max(answer, tmp);

      for (int i = 0; i < cnt; i++) {
        tmp += cycle[(start + i) % m];
        answer = max(answer, tmp);
      }
    }
  }

  cout << answer << '\n';

}

Submission status: Runtime Error

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

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

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

lps=[]
vtd=[False]*n
for i in range(n):
    if vtd[i]:continue
    now=p[i]
    vtd[now]=True
    vc=set()
    vc.add(now)
    while now!=i:
        now=p[now]
        vtd[now]=True
        vc.add(now)
    point=0
    for v in vc:
        point+=c[v]
    lps.append((list(vc),point))
# print(lps)
anslist=[]
for lp in lps:
    loop=lp[0]
    ls=len(loop)
    point=lp[1]
    if point<=0:
        ans=max(c)
        for first in loop:
            tmp=0
            now=first
            for j in range(min(k,ls)):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans)

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

Submission status: Runtime Error

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

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

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

lps=[]
vtd=[False]*n
for i in range(n):
    if vtd[i]:continue
    now=p[i]
    vtd[now]=True
    vc=set()
    vc.add(now)
    while now!=i:
        now=p[now]
        vtd[now]=True
        vc.add(now)
    point=0
    for v in vc:
        point+=c[v]
    lps.append((list(vc),point))
# print(lps)
anslist=[]
for lp in lps:
    loop=lp[0]
    ls=len(loop)
    point=lp[1]
    if point<=0:
        ans=max(c)
        for first in loop:
            tmp=0
            now=first
            for j in range(min(k,ls)):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans)
        s=vc[100000]
    if point>0:
        ans=max(c)
        for first in loop:
            tmp=0
            now=first
            for j in range(k%ls+1):
                now=p[now]
                tmp+=c[now]
                ans=max(ans,tmp)
        anslist.append(ans+point*(k//ls-1))
print(max(anslist))

Submission status: Runtime Error

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

ans = -float('inf')

for i in range(n): #start
    start = i
    now = start
    total = 0
    ls = [0]

    for j in range(1, k+1):
        now = pn[now]-1
        total += cn[now]
        ans = max(ans, total)
        ls.append(total)
        if now == start:
            rp = j
            break
    else:
        continue

    if total <= 0:
        continue
    else:
        s = k % rp
        ans2 = total * (k//rp) + max(ls[:s])
        ans = max(ans, ans2)
print(ans)

Submission status: Runtime Error

Solution code:
p = []
c = []

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

i = 1
while(i<=n):
    d = [0]*n
    visited = [0]*n
    cnt = 0
    j=i
    answ=0
    last=i
    while(cnt<k and visited[j]==False):
        cnt+=1
        visited[j] = cnt
        d[j] = answ
        last = j
        j = p[j]
        answ+=c[j]
        best[i] = max(best[i],answ)
    
    k1 = max(k-cnt,0)
    cycle = visited[last]-visited[j]+1
    answ += (answ-d[j])*(k1//cycle)
    best[i] = max(best[i],answ)
    k1 = k1%cycle
    while(k1>0):
        j = p[j]
        answ+=c[j]
        best[i] = max(best[i],answ)
        k1-=1
    i+=1


print(max(best))

Submission status: Runtime Error

Solution code:
p = []
c = []

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

i = 1
while(i<=n):
    d = [0]*n
    visited = [0]*n
    cnt = 0
    j=i
    answ=0
    last=i
    while(cnt<k and visited[j]==False):
        cnt+=1
        visited[j] = cnt
        d[j] = answ
        last = j
        j = p[j]
        answ+=c[j]
        best[i] = max(best[i],answ)
    
    k1 = max(k-cnt,0)
    cycle = visited[last]-visited[j]+1
    answ += (answ-d[j])*(k1//cycle)
    best[i] = max(best[i],answ)
    k1 = k1%cycle
    while(k1>0):
        j = p[j]
        answ+=c[j]
        best[i] = max(best[i],answ)
        k1-=1
    i+=1


print(max(best))

Submission status: Runtime Error

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

ans = -float('inf')

for i in range(n): #start
    start = i
    now = start
    total = 0
    ls = [0]

    for j in range(1, k+1):
        now = pn[now]-1
        total += cn[now]
        ans = max(ans, total)
        ls.append(total)
        if now == start:
            rp = j
            print(ls)
            break
    else:
        continue

    if total <= 0:
        continue
    else:
        if k % rp == 0:
            ans = max(ans, total * (k//rp))
        else:
            s = k % rp
            ans2 = total * (k//rp) + max(ls[:s+1])
            ans = max(ans, ans2)
print(ans)

Submission status: Runtime Error

Solution code:
import bisect,collections,copy,heapq,itertools,math,string
from collections import defaultdict as D
from functools import reduce
import numpy as np
import sys
import os
from operator import mul
from numba import njit, b1, i4, i8, f8

sys.setrecursionlimit(10**7)

def _S(): return sys.stdin.readline().rstrip()
def I(): return int(_S())
def LS(): return list(_S().split())
def LI(): return list(map(int,LS()))

if os.getenv("LOCAL"):
    inputFile = basename_without_ext = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
    sys.stdin = open(inputFile, "r")
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353    

N,K = LI()
P = LI()
C = LI()
C = np.array(C,dtype='int')
P = list(map(lambda x:x-1,P))
P = np.array(P,dtype='int')

# def rec(visited,next,s):
#     if next in s:
#         return visited,visited.index(next)
#     else:
#         s.add(next)
#         visited.append(next)
#         return rec(visited,P[next],s)

@njit((i8, i8[:], i8[:]), cache=True)
def solve(K,P,C):
    N = len(P)
    # INF = 1 << 60
    best_score = -INF
    for i in range(N):
        s = set([i])
        visited = [i]
        a = 0
        # visited,loopStart = rec(visited,P[i],s)
        next = P[i]
        while True:
            if next in s:
                loopStart = visited.index(next)
                break
            else:
                s.add(next)
                visited.append(next)
                next = P[next]

        # print(visited,loopStart)
        al = np.zeros(len(visited))
        # al = np.array([],dtype='int')
        if K < len(visited):
            for j in range(len(visited)-1):
                # al = np.append(al,C[visited[j+1]])
                al[j+1]=C[visited[j+1]]
            # print(al)
            # a_cum = np.array([],dtype='int')
            a_cum = np.zeros(len(al))
            a_cum = al.cumsum()
            a = a_cum.max()
            # print(a)
            # a = acum.max()
        else:        
            for j in range(len(visited)-1):
                al = np.append(al,C[visited[j+1]])
            visitedLoop = visited[loopStart:]
            # print("visitedLoop: ",visitedLoop)
            sum_visitedLoop = 0
            for j in range(len(visitedLoop)):
                sum_visitedLoop += C[visitedLoop[j]]
            if sum_visitedLoop<=0:
                a = al.cumsum().max()
            else:
                # 残り回数を循環配列の長さで割った余り
                q,mod = divmod((K-len(visited)),len(visitedLoop))
                # print('q,mod:',q,mod)
                # am = np.array([0],dtype='int')
                am = np.zeros(mod)

                for j in range(mod+1):
                    # am = np.append(am,C[visitedLoop[j]])
                    am[j] = C[visitedLoop[j]]
                    am_sum = am.cumsum().max()
                # print(am)
                # print('al:',al)
                # print(al.cumsum()[-1],q,sum_visitedLoop, am_sum)
                a = al.cumsum()[-1] + q*sum_visitedLoop + am_sum
        best_score = max(best_score, a)
    return best_score

res = solve(K,P,C)
print(res)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
pos = [int(i) for i in input().split()]
score = [int(i) for i in input().split()]
if max(score) <= 0:
  print(max(score))
else:
  pos = [0] + pos
  score = [0] + score
  max_point = -10 ** 10
  s_l = [[0]]
  nei = {}
  dic = {}
  loop = 0
  for i in range(1, n + 1):
    f_pos = i
    #print('f_pos',f_pos)
    points = [0]
    count = 0
    if f_pos not in nei:
      loop += 1
      while True:
        n_pos = pos[f_pos]
        points.append(points[-1] + score[n_pos])
        count += 1
        nei[f_pos] = [count, loop]
        if n_pos in nei:
          dic[loop] = count
          break
        f_pos = n_pos
      #print(points)
      #print(nei)
      s_l.append(points)
      loop_num = count
      count = 1
    else:
      loop = nei[f_pos][1]
      count = nei[f_pos][0]
      loop_num = dic[loop]
      points = s_l[loop]
    s = points[count - 1]
    m = points[loop_num] - s
    a = k // loop_num
    b = k % loop_num
    if points[loop_num] > 0:
      point = points[loop_num] * a
    else:
      point = 0
      b = loop_num
    if b > 0:
      if loop_num - count + 1 >= b:
        t_max = -10 ** 10
        for j in range(b):
          t = points[j + count] - s
          if t > t_max:
            t_max = t
      else:
        t_max = -10 ** 10
        for j in range(count, loop_num + 1):
          t = points[j] - s
          if t > t_max:
            t_max = t
        for j in range(1, b - loop_num + count):
          t = points[j] + m
          if t > t_max:
            t_max = t
      point += t_max
    #print(point)
    if point > max_point:
      max_point = point
  print(max_point)

Submission status: Runtime Error

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

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

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import bisect,collections,copy,heapq,itertools,math,string
from collections import defaultdict as D
from functools import reduce
import numpy as np
import sys
import os
from operator import mul
from numba import njit

sys.setrecursionlimit(10**7)

def _S(): return sys.stdin.readline().rstrip()
def I(): return int(_S())
def LS(): return list(_S().split())
def LI(): return list(map(int,LS()))

if os.getenv("LOCAL"):
    inputFile = basename_without_ext = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
    sys.stdin = open(inputFile, "r")
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353    

N,K = LI()
P = LI()
C = LI()
C = np.array(C,dtype='int')
P = list(map(lambda x:x-1,P))
P = np.array(P,dtype='int')

# def rec(visited,next,s):
#     if next in s:
#         return visited,visited.index(next)
#     else:
#         s.add(next)
#         visited.append(next)
#         return rec(visited,P[next],s)

@njit
def solve(N,K,P,C):
    ans = [0] * N
    for i in range(N):
        s = set([i])
        visited = [i]
        a = 0
        # visited,loopStart = rec(visited,P[i],s)
        next = P[i]
        while True:
            if next in s:
                loopStart = visited.index(next)
                break
            else:
                s.add(next)
                visited.append(next)
                next = P[next]

        # print(visited,loopStart)
        al = np.zeros(len(visited))
        # al = np.array([],dtype='int')
        if K < len(visited):
            for j in range(len(visited)-1):
                # al = np.append(al,C[visited[j+1]])
                al[j+1]=C[visited[j+1]]
            # print(al)
            # a_cum = np.array([],dtype='int')
            a_cum = np.zeros(len(al))
            a_cum = al.cumsum()
            a = a_cum.max()
            # print(a)
            # a = acum.max()
        else:        
            for j in range(len(visited)-1):
                al = np.append(al,C[visited[j+1]])
            visitedLoop = visited[loopStart:]
            # print("visitedLoop: ",visitedLoop)
            sum_visitedLoop = 0
            for j in range(len(visitedLoop)):
                sum_visitedLoop += C[visitedLoop[j]]
            if sum_visitedLoop<=0:
                a = al.cumsum().max()
            else:
                # 残り回数を循環配列の長さで割った余り
                q,mod = divmod((K-len(visited)),len(visitedLoop))
                # print('q,mod:',q,mod)
                # am = np.array([0],dtype='int')
                am = np.zeros(mod)

                for j in range(mod+1):
                    # am = np.append(am,C[visitedLoop[j]])
                    am[j] = C[visitedLoop[j]]
                    am_sum = am.cumsum().max()
                # print(am)
                # print('al:',al)
                # print(al.cumsum()[-1],q,sum_visitedLoop, am_sum)
                a = al.cumsum()[-1] + q*sum_visitedLoop + am_sum
        ans[i]=a
    return ans
res = solve(N,K,P,C)
print(max(res))

Submission status: Runtime Error

Solution code:
[n, k] = map(int, input().split())
strp = input().split()
strc = input().split()
p = [0]
c = [0]
for i in range(n):
	p.append(int(strp[i]))
	c.append(int(strc[i]))

# p[1].append(123)
# print(p)
# print(c)
chain = [[i] for i in range(n+1)]
score = [[c[i]] for i in range(n+1)]

# set chain and score
for i in range(1,n+1):
	next = p[i]
	while(i != next):
		chain[i].append(next)
		score[i].append(score[i][-1] + c[next])
		next = p[next]

bests = [0]
for i in range(1,n+1):
	l = len(chain[i])
	lastlen = k%l
	if score[i][-1] <= 0:
		tmp = c[i]
		if k%l == 0:
			lastlen = l
		# for j in range(lastlen):
		# 	if score[i][j] > tmp:
		# 		tmp = score[i][j]
		best = max(score[i][1:lastlen])
	else:
		div = int(k/l)
		if k%l == 0:
			lastlen = l
			div -= 1
		best = div*score[i][-1]
		tmp = c[i]
		# for j in range(k%l):
		# 	if score[i][j] > tmp:
		# 		tmp = score[i][j]
		best += max(score[i][1:lastlen])
		# best += max(score[i][:k%l])
	bests.append(best)
# print(bests[])
print(max(bests[1:]))
# print(p)
# print(c)
# print(chain)
# print(score)

Submission status: Runtime Error

Solution code:
    n,k=(int(x) for x in input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
     
    x=-10000000000
    for i in range(n):
        m=i
        cn=[]
        cnt=0
        l=0
        while l<k:
            m=p[m]-1
            cnt += c[m]
            l+=1
            if i==m:
                l1=k//l
                cnt*=l1
                l=k-k%l
            cn.append(cnt)
            #print(cn,l)
        x=max(x,max(cn))
    print(x)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
pos = [int(i) for i in input().split()]
score = [int(i) for i in input().split()]
if max(score) <= 0:
  print(max(score))
else:
  pos = [0] + pos
  score = [0] + score
  max_point = -10 ** 10
  s_l = [[0]]
  nei = {}
  dic = {}
  loop = 0
  for i in range(1, n + 1):
    f_pos = i
    #print('f_pos',f_pos)
    points = [0]
    count = 0
    if f_pos not in nei:
      loop += 1
      while True:
        n_pos = pos[f_pos]
        points.append(points[-1] + score[n_pos])
        count += 1
        nei[f_pos] = [count, loop]
        if n_pos in nei:
          dic[loop] = count
          break
        f_pos = n_pos
      #print(points)
      #print(nei)
      s_l.append(points)
      loop_num = count
      count = 1
    else:
      loop = nei[f_pos][1]
      count = nei[f_pos][0]
      loop_num = dic[loop]
      points = s_l[loop]
    s = points[count - 1]
    m = points[loop_num] - s
    a = k // loop_num
    b = k % loop_num
    if points[loop_num] > 0:
      point = points[loop_num] * a
      if b > 0:
        if loop_num - count + 1 >= b:
          t_max = -10 ** 10
          for j in range(b):
            t = points[j + count] - s
            if t > t_max:
              t_max = t
        else:
          t_max = -10 ** 10
          for j in range(count, loop_num + 1):
            t = points[j] - s
            if t > t_max:
              t_max = t
          for j in range(1, b - loop_num + count):
            t = points[j] + m
            if t > t_max:
              t_max = t
        point += t_max
    else:
      point = max(points)
    #print(point)
    if point > max_point:
      max_point = point
  print(max_point)

Submission status: Runtime Error

Solution code:
import sys
from itertools import islice, repeat


def _resolve(costs, k):
    sum_ = sum(costs)
    v = 0
    if k >= len(costs):
        if sum_ > 0:
            x = k // len(costs) - 1
            v = x * sum_
            k -= x * len(costs)
        else:
            k = len(costs)

    points = [v] * (len(costs) * (k + 1))
    for i in range(k):
        for n in range(len(costs)):
            points[(i + 1) * len(costs) + n] = points[i * len(costs) + n] + costs[(i + n) % len(costs)]
    
    ans = max(points)
    if ans == 0:
        y = max(costs)
        if y < 0:
            ans = y
    return ans


def resolve(in_):
    N, K = map(int, next(in_).split())
    P = list(map(int, next(in_).split())
    C = [0] + list(map(int, next(in_).split()))

    graphs = []
    p = set(P)
    while p:
        index = p.pop()
        graph = [C[index]]
        index = P[index]
        while index in p:
            graph.append(C[index])
            p.remove(index)
            index = P[index]
        graphs.append(graph)

    ans = max(map(_resolve, graphs, repeat(K)))
    return ans


def main():
    answer = resolve(sys.stdin.buffer)
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

seen=[False]*n
max_sum=0
log=0
max_loop=[]
loop=[]
cnt=0
i=0
while cnt<=n-1:
  if seen[i]==True:
    if max_sum<log:
      max_loop=loop
      max_sum=log
    log=0  
    loop=[]
    i=0
    while not seen[i]　and cnt<=n-1:i+=1
  seen[i]==True
  loop.append(c[i])
  log=max(log,log+c[i])
  
  i=p[i]
  cnt+=1


max_loop=sorted(max_loop,reverse=True)
print(max_sum*(k//len(max_loop))+sum(max_loop[:k%len(max_loop)]))

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
pos = [int(i) for i in input().split()]
score = [int(i) for i in input().split()]
if max(score) <= 0:
  print(max(score))
else:
  pos = [0] + pos
  score = [0] + score
  max_point = -10 ** 10
  s_l = [[0]]
  nei = {}
  dic = {}
  loop = 0
  for i in range(1, n + 1):
    f_pos = i
    #print('f_pos',f_pos)
    points = [0]
    count = 0
    if f_pos not in nei:
      loop += 1
      while True:
        n_pos = pos[f_pos]
        points.append(points[-1] + score[n_pos])
        count += 1
        nei[f_pos] = [count, loop]
        if n_pos in nei:
          dic[loop] = count
          break
        f_pos = n_pos
      #print(points)
      #print(nei)
      s_l.append(points)
      loop_num = count
    else:
      loop = nei[f_pos][1]
      count = nei[f_pos][0]
      loop_num = dic[loop]
      s = s_l[loop][count - 1]
      for j in range(count, loop_num + 1):
        points.append(s_l[loop][j] - s)
      s = s_l[loop][loop_num] - s
      for j in range(1, count):
        points.append(s_l[loop][j] + s)
      #print(points)
    a = k // loop_num
    b = k % loop_num
    if points[loop_num] > 0:
      point = points[loop_num] * a
      if b > 0:
        point += max(points[1:b + 1])
    else:
      point = max(points)
    #print(point)
    if point > max_point:
      max_point = point
  print(max_point)

Submission status: Runtime Error

Solution code:
#include<bits/stdc++.h>
#define rep(i,n) for(int i=0;i<n;i++)
#define INF 1000000007
using namespace std;


int main(){
  long n,k;
  cin >> n >> k;
  long p[n],c[n];
  rep(i,n){
    cin >> p[i];
    p[i]--;
  }
  rep(i,n)cin >> c[i];
  long maxsum = -INF, ans = -INF;
  long flag[n][n];
  rep(i,n)rep(j,n)flag[i][j] = 0;
  rep(i,n){
    long tmp_max = -INF, tmp = 0, now = i, iter = 0;
    while(1){
      if(flag[i][now]==1 || iter >= k)break;
      now = p[now];
      tmp += c[now];
      if(tmp > tmp_max)tmp_max = tmp;
      iter++;
    }
    if(tmp_max > ans)ans = tmp_max;
    if(iter < k){
      long score = (k/iter)*tmp + (k%iter)*tmp_max;
      if(score > ans)ans = score;
    }
  }
  
  cout << ans << endl;
  return 0;
}

Submission status: Runtime Error

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]
    
    cum_sum=[0]
    for sss in cycle: cum_sum.append(cum_sum[-1]+sss)    
    
    if k<=len(cycle):
        ss=cum_sum[1]
        for j in range(k):
            if cum_sum[j+1]>ss:
                ss=cum_sum[j+1]
        ans.append(ss)
    else:
        s=sum(cycle)*(k//len(cycle)) 
        ss=cum_sum[1]
        for j in range(1,k%len(cycle)):
            if cum_sum[j+1]>ss:
                ss=cum_sum[j+1]
        mm=max(ss+s,s)
        
        ss=cum_sum[1]
        for j in range(len(cycle)-1):
            if cum_sum[j+1]>ss:
                ss=cum_sum[j+1]
        ans.append(max(mm,ss))
        
    
print(max(ans))#!/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]
    
    cum_sum=[0]
    for sss in cycle: cum_sum.append(cum_sum[-1]+sss)    
    
    if k<=len(cycle):
        ss=cum_sum[1]
        for j in range(k):
            if cum_sum[j+1]>ss:
                ss=cum_sum[j+1]
        ans.append(ss)
    else:
        s=sum(cycle)*(k//len(cycle)) 
        ss=cum_sum[1]
        for j in range(1,k%len(cycle)):
            if cum_sum[j+1]>ss:
                ss=cum_sum[j+1]
        mm=max(ss+s,s)
        
        ss=cum_sum[1]
        for j in range(len(cycle)-1):
            if cum_sum[j+1]>ss:
                ss=cum_sum[j+1]
        ans.append(max(mm,ss))
        
    
print(max(ans))