input stringlengths 20 127k | target stringlengths 20 119k | problem_id stringlengths 6 6 |
|---|---|---|
import copy
MOD = 10 ** 9 + 7
def make_list(*args):
r = [0] * args[-1]
for n in args[len(args) - 2::-1]:
r = [copy.deepcopy(r) for _ in range(n)]
return r
N = int(eval(input()))
dp = make_list(N + 1, 5, 5, 5)
dp[0][0][0][0] = 1
# INIT = 0, A = 1, C = 2, G = 3, T = 4
for n in range(N):
for i in range(5):
for j in range(5):
for k in range(5):
for l in range(1, 5):
# AGC
if j == 1 and k == 3 and l == 2:
continue
# GAC
if j == 3 and k == 1 and l == 2:
continue
# ACG
if j == 1 and k == 2 and l == 3:
continue
# A*GC
if i == 1 and k == 3 and l == 2:
continue
# AG*C
if i == 1 and j == 3 and l == 2:
continue
dp[n + 1][j][k][l] += dp[n][i][j][k]
dp[n + 1][j][k][l] %= MOD
r = 0
for i in range(1, 5):
for j in range(1, 5):
for k in range(1, 5):
r += dp[N][i][j][k]
r %= MOD
print(r)
| import math, heapq
from operator import itemgetter as ig
from collections import defaultdict as dd
# 定数
INF = float("inf")
MOD = int(1e9 + 7)
# データ構造:ヒープ
class heapque:
def __init__(self, *args):
self.que = []
for arg in args:
self.push(arg)
def push(self, v):
heapq.heappush(self.que, v)
def pop(self):
return heapq.heappop(self.que)
# 最大公約数 / 最小公倍数
def gcd(v1, v2):
if v2 == 0:
return v1
return gcd(v2, v1 % v2)
def lcm(v1, v2):
return (v1 // gcd(v1, v2)) * v2
# 二分探索
def bsr(a, v, lo=0, hi=None):
if hi == None:
hi = len(a) - 1
if hi < lo:
return lo
mi = (lo + hi) // 2
if v < a[mi]:
return bsr(a, v, lo, mi - 1)
else:
return bsr(a, v, mi + 1, hi)
# Union-Find木
class uft:
def __init__(self, n):
self.height = [1] * n
self.group = [-1] * n
def root(self, v):
if self.group[v] < 0:
return v
self.group[v] = self.root(self.group[v])
return self.group[v]
def size(self, v):
return - self.group[self.root(v)]
def merge(self, v1, v2):
v1, v2 = self.root(v1), self.root(v2)
if v1 == v2:
return
if self.height[v1] < self.height[v2]:
self.group[v2] += self.group[v1]
self.group[v1] = v2
self.height[v2] = max(self.height[v1] + 1, self.height[v2])
else:
self.group[v1] += self.group[v2]
self.group[v2] = v1
self.height[v1] = max(self.height[v1] , self.height[v2] + 1)
# グラフ
class graph:
def __init__(self, n):
self.n = n
self.graph = [[] for _ in range(n)]
def append(self, v1, v2, cost=1):
self.graph[v1].append((v2, cost))
# 最短経路:ダイクストラ法(Dijkstra's Algorithm)
def dks(self, v):
costs = [INF] * self.n
costs[v] = 0
done = [False] * self.n
heap = heapque((0, v))
while heap.que:
c_cost, c_index = heap.pop()
if done[c_index]:
continue
done[c_index] = True
for n_index, n_cost in self.graph[c_index]:
if c_cost + n_cost < costs[n_index]:
costs[n_index] = c_cost + n_cost
heap.push((costs[n_index], n_index))
return costs
def main():
N = int(eval(input()))
dp = [[[[0 for _ in range(5)] for _ in range(5)] for _ in range(5)] for _ in range(N + 1)]
dp[0][0][0][0] = 1
for i in range(N):
for j in range(5):
for k in range(5):
for l in range(5):
for m in range(1, 5):
if k == 1 and l == 3 and m == 2: continue
if k == 1 and l == 2 and m == 3: continue
if k == 3 and l == 1 and m == 2: continue
if j == 1 and l == 3 and m == 2: continue
if j == 1 and k == 3 and m == 2: continue
dp[i + 1][k][l][m] += dp[i][j][k][l]
dp[i + 1][k][l][m] %= MOD
r = 0
for i in range(1, 5):
for j in range(1, 5):
for k in range(1, 5):
r += dp[-1][i][j][k]
r %= MOD
print(r)
main()
| p03088 |
#x=int(input())
n=int(eval(input()))
m=102
chars=['A','T','C','G']
mo=10**9+7
d3=set()
d4=set()
for i in chars:
for j in chars:
for k in chars:
d3.add(i+j+k)
for l in chars:
d4.add(i+j+k+l)
kinsoku4=set()
kinsoku3=['AGC','ACG','GAC']
for y in chars:
kinsoku4.add('AG'+y+'C')
kinsoku4.add('A'+y+'GC')
for z in kinsoku3:
kinsoku4.add(y+z)
kinsoku4.add(z+y)
dp=[dict() for i in range(m)]
cnt=[0]*m
for i in d4:
if i not in kinsoku4:
dp[4][i]=1
t=101
for i in range(4,t):
for ch in chars:
for p in list(dp[i-1].keys()):
if p[1:4]+ch not in kinsoku4:
if p[1:4]+ch in dp[i]:
dp[i][p[1:4]+ch]+=dp[i-1][p]%mo
else:
dp[i][p[1:4]+ch]=dp[i-1][p]%mo
for i in range(t):
for x in d4:
if x not in kinsoku4 and x in dp[i]:
cnt[i]+=dp[i][x]%mo
cnt[i]%=mo
#print(len(kinsoku4),kinsoku4)
#print(dp)
#for x in cnt:
#print(x%mo)
if n==3:
ans=61
print(ans)
else:
print((cnt[n]))
| n=int(eval(input()))
m=102
chars=['A','T','C','G']
mo=10**9+7
d4=set()
for i in chars:
for j in chars:
for k in chars:
for l in chars:
d4.add(i+j+k+l)
kinsoku4=set()
kinsoku3=['AGC','ACG','GAC']
for y in chars:
kinsoku4.add('AG'+y+'C')
kinsoku4.add('A'+y+'GC')
for z in kinsoku3:
kinsoku4.add(y+z)
kinsoku4.add(z+y)
dp=[dict() for i in range(m)]
cnt=[0]*m
for i in d4:
if i not in kinsoku4:
dp[4][i]=1
t=1+n
for i in range(4,t):
for ch in chars:
for p in list(dp[i-1].keys()):
if p[1:4]+ch not in kinsoku4:
if p[1:4]+ch in dp[i]:
dp[i][p[1:4]+ch]+=dp[i-1][p]%mo
else:
dp[i][p[1:4]+ch]=dp[i-1][p]%mo
for i in range(t):
for x in d4:
if x not in kinsoku4 and x in dp[i]:
cnt[i]+=dp[i][x]%mo
cnt[i]%=mo
if n==3:
ans=61
print(ans)
else:
print((cnt[n]))
| p03088 |
def main():
n = int(eval(input()))
MOD = 10 ** 9 + 7
note = [{} for _ in range(n+1)]
def ok(last4):
for i in range(4):
t = list(last4)
if i >= 1:
t[i-1], t[i] = t[i], t[i-1]
if ''.join(t).count('AGC') >= 1:
return False
return True
def dfs(cur, last3):
if last3 in note[cur]:
return note[cur][last3]
if cur == n:
return 1
ret = 0
for c in 'ACGT':
if ok(last3 + c):
ret += dfs(cur + 1, last3[1:] + c)
ret %= MOD
note[cur][last3] = ret
return ret
print((dfs(0, 'TTT')))
main()
| # from https://atcoder.jp/contests/abc122/submissions/4932940
def main():
n = int(eval(input()))
MOD = 10 ** 9 + 7
dpa = [0, 0, 1]
dpc = [0, 0, 1]
dpg = [0, 0, 1]
dpt = [0, 0, 1]
for i in range(2, n + 2):
total = dpa[i] + dpc[i] + dpg[i] + dpt[i]
if i == n + 1:
break
dpa.append(total)
dpc.append(total - dpa[i-1] - dpg[i-1] - 3 * dpa[i-2])
dpg.append(total - dpa[i-1] + dpg[i-2])
dpt.append(total)
print((total % MOD))
main()
| p03088 |
N = int(eval(input()))
memo = [{} for i in range(N + 1)]
MOD = 10 ** 9 + 7
def ok(last4):
for i in range(4):
t = list(last4)
if i >= 1:
t[i], t[i - 1] = t[i - 1], t[i]
if "".join(t).count("AGC") >= 1:
return False
return True
def dfs(cur, last3):
if last3 in memo[cur]:
return memo[cur][last3]
if cur == N:
return 1
ret = 0
for c in "ACGT":
if ok(last3 + c):
ret = ret + dfs(cur + 1, last3[1:] + c)
memo[cur][last3] = ret
return ret
print((dfs(0, "TTT") % MOD)) | N = int(eval(input()))
MOD = 10 ** 9 + 7
memo = [{} for i in range(N + 1)]
def ok(last4):
for i in range(4):
t = list(last4)
if i >= 1:
t[i], t[i - 1] = t[i - 1], t[i]
if "".join(t).count("AGC") >= 1:
return False
return True
def dfs(cur, last3):
if last3 in memo[cur]:
return memo[cur][last3]
if cur == N:
return 1
ret = 0
for c in "ACGT":
if ok(last3 + c):
ret = ret + dfs(cur + 1, last3[1:] + c)
memo[cur][last3] = ret
return ret
print((dfs(0, "TTT") % MOD)) | p03088 |
mod = 1000000007
N = int(eval(input()))
dp = [ [[[0 for c3 in range(4)] for c2 in range(4)] for c1 in range(4)] for n in range(N+1)]
# 全部TのときはOK
dp[0][3][3][3] = 1
# 文字の数
for n in range(N):
# 後ろから1文字目
for c1 in range(4):
# 後ろから2文字目
for c2 in range(4):
# 後ろから3文字目
for c3 in range(4):
# 該当するものがないとき
if dp[n][c1][c2][c3] == 0: continue
# 新しく追加する文字
for a in range(4):
# AGCに当てはまる文字
if(c2 == 0 and c1 == 1 and a == 2): continue
if(c2 == 0 and c1 == 2 and a == 1): continue
if(c2 == 1 and c1 == 0 and a == 2): continue
if(c3 == 0 and c1 == 1 and a == 2): continue
if(c3 == 0 and c2 == 1 and a == 2): continue
dp[n+1][a][c1][c2] += dp[n][c1][c2][c3]
dp[n+1][a][c1][c2] %= mod
ans = 0
# 後ろから1文字目
for c1 in range(4):
# 後ろから2文字目
for c2 in range(4):
# 後ろから3文字目
for c3 in range(4):
ans += dp[N][c1][c2][c3]
ans %= mod
print(ans) | # DPをつかった解放を全然思いつけなかった
# 解説動画がわかりやすい
mod = 1000000007
N = int(eval(input()))
dp = [ [[[0 for c3 in range(4)] for c2 in range(4)] for c1 in range(4)] for n in range(N+1)]
# 全部TのときはOK
dp[0][3][3][3] = 1
# 文字の数
for n in range(N):
# 後ろから1文字目
for c1 in range(4):
# 後ろから2文字目
for c2 in range(4):
# 後ろから3文字目
for c3 in range(4):
# 該当するものがないとき
if dp[n][c1][c2][c3] == 0: continue
# 新しく追加する文字
for a in range(4):
# AGCに当てはまる文字
if(c2 == 0 and c1 == 1 and a == 2): continue
if(c2 == 0 and c1 == 2 and a == 1): continue
if(c2 == 1 and c1 == 0 and a == 2): continue
if(c3 == 0 and c1 == 1 and a == 2): continue
if(c3 == 0 and c2 == 1 and a == 2): continue
dp[n+1][a][c1][c2] += dp[n][c1][c2][c3]
ans = 0
# 後ろから1文字目
for c1 in range(4):
# 後ろから2文字目
for c2 in range(4):
# 後ろから3文字目
for c3 in range(4):
ans += dp[N][c1][c2][c3]
print((ans % mod)) | p03088 |
n=int(eval(input()))
A,C,G,T,M=0,1,2,3,10**9+7
r=range
dp=[[[[0]*4for k in r(4)]for j in r(4)]for i in r(n+1)]
dp[0][T][T][T]=1
for i in r(1,n+1):
for j in r(4):
for k in r(4):
for l in r(4):
for m in r(4):
if any(t==(k,l,m)for t in((A,G,C),(A,C,G),(G,A,C)))or(j,l,m)==(A,G,C)or(j,k,m)==(A,G,C):continue
dp[i][k][l][m]=(dp[i][k][l][m]+dp[i-1][j][k][l])%M
print((sum(dp[n][i][j][k]for i in r(4)for j in r(4)for k in r(4))%M)) | n=int(eval(input()))
A,C,G,T,M,R=0,1,2,3,10**9+7,list(range(4))
dp=[[[[0]*4for k in R]for j in R]for i in range(n+1)]
dp[0][T][T][T]=1
for i in range(1,n+1):
for j in R:
for k in R:
for l in R:
for m in R:
if not(any(t==(k,l,m)for t in((A,G,C),(A,C,G),(G,A,C)))or(j,l,m)==(A,G,C)or(j,k,m)==(A,G,C)):dp[i][k][l][m]=(dp[i][k][l][m]+dp[i-1][j][k][l])%M
print((sum(c for a in dp[n]for b in a for c in b)%M)) | p03088 |
n=int(eval(input()))
A,C,G,T,M,R=0,1,2,3,10**9+7,list(range(4))
dp=[[[[0]*4for k in R]for j in R]for i in range(n+1)]
dp[0][T][T][T]=1
for i in range(1,n+1):
for j in R:
for k in R:
for l in R:
for m in R:
if not(any(t==(k,l,m)for t in((A,G,C),(A,C,G),(G,A,C)))or(j,l,m)==(A,G,C)or(j,k,m)==(A,G,C)):dp[i][k][l][m]=(dp[i][k][l][m]+dp[i-1][j][k][l])%M
print((sum(c for a in dp[n]for b in a for c in b)%M)) | print(((388130742,597534442,616680192,329869205,170591295,333099663,133009077,738390145,866398347,718889563,252858375,847205021,915711339,123820509,940737264,371653459,323137024,353770801,206282374,847501730,25328739,842176273,569725155,781042769,427196161,570246669,191483611,673385295,324759692,245601370,975058685,406959393,515140586,305799096,981760191,986519078,414054379,149602322,221791721,792638194,696683714,725438992,702530485,51018086,751629411,971550783,664630886,256852905,775465589,799008836,113468411,39816123,501575626,124885216,998121103,181836645,639213333,123883652,785892908,763737161,534833116,978442997,88638656,604356692,409213624,68697295,649970414,855462856,783022045,23314687,531294469,996291083,549054109,639056669,858533109,159693437,604119499,737209731,44657419,51688048,580025381,776803305,261943303,733354121,794717734,478366600,127504505,33985227,9058467,2414454,643550,171531,45719,12185,3247,865,230,61)[2-int(eval(input()))])) | p03088 |
n=int(eval(input()))
A,C,G,T,M,R=0,1,2,3,10**9+7,list(range(4))
dp=[[[[0]*4for k in R]for j in R]for i in range(n+1)]
dp[0][T][T][T]=1
for i in range(1,n+1):
for j in R:
for k in R:
for l in R:
for m in R:
if(G,A,C)!=(k,l,m)!=(A,C,G)!=(k,l,m)!=(A,G,C)!=(j,l,m)!=(A,G,C)!=(j,k,m):dp[i][k][l][m]=(dp[i][k][l][m]+dp[i-1][j][k][l])%M
print((sum(c for a in dp[n]for b in a for c in b)%M)) | n=int(eval(input()))
M,R=10**9+7,list(range(4))
dp=[[[[0]*4for k in R]for j in R]for i in range(n+1)]
dp[0][3][3][3]=1
for i in range(1,n+1):
for j in R:
for k in R:
for l in R:
for m in R:
if(2,0,1)!=(k,l,m)!=(0,1,2)!=(k,l,m)!=(0,2,1)!=(j,l,m)!=(0,2,1)!=(j,k,m):dp[i][k][l][m]=(dp[i][k][l][m]+dp[i-1][j][k][l])%M
print((sum(c for a in dp[n]for b in a for c in b)%M)) | p03088 |
n=int(eval(input()))
M,R=10**9+7,list(range(4))
dp=[[[[0]*4for k in R]for j in R]for i in range(n+1)]
dp[0][3][3][3]=1
for i in range(1,n+1):
for j in R:
for k in R:
for l in R:
for m in R:
if(2,0,1)!=(k,l,m)!=(0,1,2)!=(k,l,m)!=(0,2,1)!=(j,l,m)!=(0,2,1)!=(j,k,m):dp[i][k][l][m]=(dp[i][k][l][m]+dp[i-1][j][k][l])%M
print((sum(c for a in dp[n]for b in a for c in b)%M)) | n=int(eval(input()))
R=list(range(4))
dp=[[[[0]*4for k in R]for j in R]for i in range(n+1)]
dp[0][3][3][3]=1
for i in range(1,n+1):
for j in R:
for k in R:
for l in R:
for m in R:
if(2,0,1)!=(k,l,m)!=(0,1,2)!=(k,l,m)!=(0,2,1)!=(j,l,m)!=(0,2,1)!=(j,k,m):dp[i][k][l][m]+=dp[i-1][j][k][l]
print((sum(c for a in dp[n]for b in a for c in b)%(10**9+7))) | p03088 |
import re,functools as f
@f.lru_cache(None)
def d(n,b):return n<1or sum(d(n-1,b[1:]+s)for s in'ACGT'if not re.match('.AGC|.ACG|.GAC|A.GC|AG.C',b+s))%(10**9+7)
print((d(int(eval(input())),'TTT'))) | import re,functools as f;d=f.lru_cache(None)(lambda n,b:n<1or sum(d(n-1,b[1:]+s)for s in'ACGT'if not re.match('.AGC|.ACG|.GAC|A.GC|AG.C',b+s))%(10**9+7));print((d(int(eval(input())),'TTT'))) | p03088 |
import re,functools as f;d=f.lru_cache(999)(lambda n,b:n<1or sum(d(n-1,b[1:]+s)for s in'ACGT'if not re.match('.AGC|.ACG|.GAC|A.GC|AG.C',b+s))%(10**9+7));print((d(int(eval(input())),'TTT'))) | a=b=c=d=e=f=0;g=1;exec('a,b,c,d,e,f,g=b,e,e-d,f,g,g-c,(g*4-b-c-d-a*3)%(10**9+7);'*int(eval(input())));print(g) | p03088 |
N = int(eval(input()))
if N==3:
print((61))
exit()
MOD = 10**9+7
dp = [[0]*64 for i in range(N-2)]
A,C,G,T = 0,1,2,3
for i in range(4):
for j in range(4):
for k in range(4):
if i==A and j==G and k==C: continue
if i==A and j==C and k==G: continue
if i==G and j==A and k==C: continue
dp[0][i*16 + j*4+ k] = 1
for i in range(N-3):
for j in range(64):
a,b = divmod(j,16)
b,c = divmod(b,4)
for d in range(4):
if b==A and c==G and d==C: continue
if b==A and c==C and d==G: continue
if b==G and c==A and d==C: continue
if a==A and b==G and d==C: continue
if a==A and c==G and d==C: continue
dp[i+1][b*16+c*4+d] += dp[i][j]
dp[i+1][b*16+c*4+d] %= MOD
print((sum(dp[-1]) % MOD)) | N = int(eval(input()))
dp = [[[[0]*4 for _ in range(4)] for _ in range(4)] for _ in range(N-2)]
for i in range(4):
for j in range(4):
for k in range(4):
if i==0 and j==1 and k==2: continue #AGC
if i==0 and j==2 and k==1: continue #ACG
if i==1 and j==0 and k==2: continue #GAC
dp[0][i][j][k] = 1
MOD = 10**9+7
for i in range(N-3):
for ppp in range(4):
for pp in range(4):
for p in range(4):
for n in range(4):
if pp==0 and p==1 and n==2: continue #AGC
if pp==0 and p==2 and n==1: continue #ACG
if pp==1 and p==0 and n==2: continue #GAC
if ppp==0 and p==1 and n==2: continue #A?GC
if ppp==0 and pp==1 and n==2: continue #AG?C
dp[i+1][pp][p][n] += dp[i][ppp][pp][p]
dp[i+1][pp][p][n] %= MOD
ans = sum(sum(sum(a) for a in b) for b in dp[-1])
print((ans%MOD)) | p03088 |
n = int(eval(input()))
MOD = 10 ** 9 + 7
dp = [[[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)] for _ in range(n)]
for a in range(4):
for b in range(4):
for c in range(4):
dp[2][a][b][c] = 1
dp[2][0][1][2] = 0
dp[2][0][2][1] = 0
dp[2][1][0][2] = 0
for i in range(3, n):
for a in range(4):
for b in range(4):
for c in range(4):
dp[i][b][c][0] = (dp[i][b][c][0] + dp[i-1][a][b][c]) % MOD
dp[i][b][c][3] = (dp[i][b][c][3] + dp[i-1][a][b][c]) % MOD
if not (b == 0 and c == 2):
dp[i][b][c][1] = (dp[i][b][c][1] + dp[i-1][a][b][c]) % MOD
if not ((b == 0 and c == 1) or (b == 1 and c == 0) or (a == 0 and (b == 1 or c == 1))):
dp[i][b][c][2] = (dp[i][b][c][2] + dp[i-1][a][b][c]) % MOD
#print(dp)
ans = 0
for a in range(4):
for b in range(4):
for c in range(4):
ans = (ans + dp[n-1][a][b][c]) % MOD
print(ans) | n = int(eval(input()))
ans = [0, 0, 0, 61, 230, 865, 3247, 12185, 45719, 171531, 643550, 2414454, 9058467, 33985227, 127504505, 478366600, 794717734, 733354121, 261943303, 776803305, 580025381, 51688048, 44657419, 737209731, 604119499, 159693437, 858533109, 639056669, 549054109, 996291083, 531294469, 23314687, 783022045, 855462856, 649970414, 68697295, 409213624, 604356692, 88638656, 978442997, 534833116, 763737161, 785892908, 123883652, 639213333, 181836645, 998121103, 124885216, 501575626, 39816123, 113468411, 799008836, 775465589, 256852905, 664630886, 971550783, 751629411, 51018086, 702530485, 725438992, 696683714, 792638194, 221791721, 149602322, 414054379, 986519078, 981760191, 305799096, 515140586, 406959393, 975058685, 245601370, 324759692, 673385295, 191483611, 570246669, 427196161, 781042769, 569725155, 842176273, 25328739, 847501730, 206282374, 353770801, 323137024, 371653459, 940737264, 123820509, 915711339, 847205021, 252858375, 718889563, 866398347, 738390145, 133009077, 333099663, 170591295, 329869205, 616680192, 597534442, 388130742]
print((ans[n])) | p03088 |
import functools
N, MOD = int(eval(input())), 10 ** 9 + 7
def ok(last4):
for i in range(4):
t = list(last4)
if i >= 1:
t[i-1], t[i] = t[i], t[i-1]
if ''.join(t).count('AGC') >= 1:
return False
return True
@functools.lru_cache(maxsize=None)
def dfs(cur, last3):
if cur == N:
return 1
ret = 0
for c in 'ACGT':
if ok(last3 + c):
ret = (ret + dfs(cur + 1, last3[1:] + c)) % MOD
return ret
print((dfs(0, 'TTT')))
| import functools
N, MOD = int(eval(input())), 10 ** 9 + 7
@functools.lru_cache(maxsize=None)
def ok(last4):
for i in range(4):
t = list(last4)
if i >= 1:
t[i-1], t[i] = t[i], t[i-1]
if ''.join(t).count('AGC') >= 1:
return False
return True
@functools.lru_cache(maxsize=None)
def dfs(cur, last3):
if cur == N:
return 1
ret = 0
for c in 'ACGT':
if ok(last3 + c):
ret = (ret + dfs(cur + 1, last3[1:] + c)) % MOD
return ret
print((dfs(0, 'TTT')))
| p03088 |
import collections, itertools
N = int(eval(input()))
mod = 10**9 + 7
cd = collections.defaultdict
dp = cd(lambda: cd(lambda: cd(lambda: cd(int))))
dp[0][3][3][3] = 1
count = 0
for i in range(N):
for c0, c1, c2, c3 in itertools.product(list(range(4)), repeat=4):
A1 = [c1, c2, c3]
A2 = [c0, c2, c3]
A3 = [c0, c1, c3]
if A1 in [[0, 1, 2], [1, 0, 2], [0, 2, 1]] or [0, 1, 2] in [A2, A3]:
continue
dp[i + 1][c1][c2][c3] += dp[i][c0][c1][c2]
dp[i + 1][c1][c2][c3] %= mod
if i == N - 1:
count += dp[i][c0][c1][c2]
count %= mod
print(count)
# https://www.youtube.com/watch?v=w2AEXSloYk8
| import collections, itertools
N = int(eval(input()))
mod = 10**9 + 7
# cd = collections.defaultdict
# dp = cd(lambda: cd(lambda: cd(lambda: cd(int))))
dp = [[[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
for _ in range(N + 1)]
dp[0][3][3][3] = 1
count = 0
for i in range(N):
for c0, c1, c2, c3 in itertools.product(list(range(4)), repeat=4):
A1 = [c1, c2, c3]
A2 = [c0, c2, c3]
A3 = [c0, c1, c3]
if A1 in [[0, 1, 2], [1, 0, 2], [0, 2, 1]] or [0, 1, 2] in [A2, A3]:
continue
dp[i + 1][c1][c2][c3] += dp[i][c0][c1][c2]
dp[i + 1][c1][c2][c3] %= mod
if i == N - 1:
count += dp[i][c0][c1][c2]
count %= mod
print(count)
# https://www.youtube.com/watch?v=w2AEXSloYk8
| p03088 |
import collections, itertools
N = int(eval(input()))
mod = 10**9 + 7
dp = collections.defaultdict(int)
dp['TTTA'] = dp['TTTG'] = dp['TTTC'] = dp['TTTT'] = 1
for _ in range(N - 1):
dp2 = collections.defaultdict(int)
for p, q, r, s, t in itertools.product('AGCT', repeat=5):
if 'AGC' in [q + s + t, s + r + t, r + s + t, q + r + t, r + t + s]:
continue
else:
dp2[q + r + s + t] += dp[p + q + r + s] % mod
dp = dp2
print((sum(dp.values()) % mod))
| import collections, itertools
N = int(eval(input()))
mod = 10**9 + 7
dp = collections.defaultdict(int)
dp['TTTA'] = dp['TTTG'] = dp['TTTC'] = dp['TTTT'] = 1
for _ in range(N - 1):
dp2 = collections.defaultdict(int)
for p, q, r, s, t in itertools.product('AGCT', repeat=5):
if 'AGC' in [q + s + t, s + r + t, r + s + t, q + r + t, r + t + s]:
continue
else:
dp2[q + r + s + t] += dp[p + q + r + s]
dp = dp2
print((sum(dp.values()) % mod))
| p03088 |
from itertools import product
from copy import deepcopy
n = int(eval(input()))
mod = 10 ** 9 + 7
comp = {"A": 0, "C": 1, "G": 2, "T": 3}
dp = [[0] * (4 ** 3) for _ in range(n + 1)]
bad = [0b001001, 0b000110, 0b100001]
for i in range(4 ** 3):
if not i in bad:
dp[3][i] = 1
def is_ok(li):
for i in range(4):
tmp = deepcopy(li)
if i >= 1:
tmp[i-1], tmp[i] = tmp[i], tmp[i-1]
if "".join(tmp).count("AGC") >= 1:
return False
return True
def comp2int(li):
ret = 0
for i, e in enumerate(li):
ret += comp[e] << 2 * (2 - i)
return ret
for i in range(3, n):
for j in product(list(comp.keys()), repeat=3):
for k in list(comp.keys()):
last4 = list(j) + [k]
if is_ok(last4):
j_prev = comp2int(j)
j_nxt = comp2int(last4[1:])
dp[i+1][j_nxt] += dp[i][j_prev]
dp[i+1][j_nxt] %= mod
ans = 0
for i in range(4 ** 3):
ans += dp[n][i]
ans %= mod
print(ans)
| from itertools import product
from copy import deepcopy
n = int(eval(input()))
mod = 10 ** 9 + 7
comp = {"A": 0, "C": 1, "G": 2, "T": 3}
keys = list(comp.keys())
dp = [[0] * (4 ** 3) for _ in range(n + 1)]
bad = [0b001001, 0b000110, 0b100001]
for i in range(4 ** 3):
if not i in bad:
dp[3][i] = 1
def is_ok(li):
for i in range(4):
tmp = deepcopy(li)
if i >= 1:
tmp[i-1], tmp[i] = tmp[i], tmp[i-1]
if "".join(tmp).count("AGC") >= 1:
return False
return True
def comp2int(li):
ret = 0
for i, e in enumerate(li):
ret += comp[e] << 2 * (2 - i)
return ret
for i in range(3, n):
for last4 in product(keys, repeat=4):
last4 = list(last4)
if is_ok(last4):
j_prev = comp2int(last4[:-1])
j_nxt = comp2int(last4[1:])
dp[i+1][j_nxt] += dp[i][j_prev]
dp[i+1][j_nxt] %= mod
ans = 0
for i in range(4 ** 3):
ans += dp[n][i]
ans %= mod
print(ans)
| p03088 |
from itertools import product
from collections import defaultdict
MOD = 10**9 + 7
N = int(eval(input()))
# XAGC, XGAC, AXGC, AGXC, XACG: prohibited
A=0; C=1; G=2; T=3
cur = defaultdict(lambda: 1)
cur[(A,G,C)] = cur[(G,A,C)] = cur[(A,C,G)] = 0
for _ in range(3,N):
prev = cur
cur = defaultdict(int)
for (i,j,k,l) in product(list(range(4)),repeat=4):
if ((j,k,l)==(A,G,C) or (j,k,l)==(G,A,C) or (i,k,l)==(A,G,C) or
(i,j,l)==(A,G,C) or (j,k,l)==(A,C,G)):
continue
else:
cur[(j,k,l)] += prev[(i,j,k)]
for ijk in product(list(range(4)),repeat=3):
cur[ijk] %= MOD
ans = sum(cur.values()) % MOD
if N <= 3:
print(([1,4,16,61][N]))
else:
print(ans) | from itertools import product
from collections import defaultdict
MOD = 10**9 + 7
N = int(eval(input()))
D, L = 4, 3
AGC = list(range(L))
ATGC = list(range(D))
cur = defaultdict(lambda: 1)
# XAGC, XGAC, AXGC, AGXC, XACG: prohibited
flip = lambda x, n: x[:n] + [x[n+1],x[n]] + x[n+2:]
prohibited1 = [tuple(AGC)] + [tuple(flip(AGC,i)) for i in range(L-1)]
prohibited2 = ({(X,) + p for p in prohibited1 for X in ATGC} |
{tuple(flip([X]+AGC,0)) for X in ATGC} |
{tuple(flip(AGC+[X],L-1)) for X in ATGC})
for p in prohibited1:
cur[p] = 0
for _ in range(L,N):
prev = cur
cur = defaultdict(int)
for recent in product(ATGC, repeat=L+1):
if recent in prohibited2:
continue
else:
cur[recent[1:]] += prev[recent[:-1]]
for latest in product(ATGC, repeat=L):
cur[latest] %= MOD
ans = sum(cur.values()) % MOD
if N < L:
print((D**N))
elif N == L:
print((D**L - len(prohibited1)))
else:
print(ans) | p03088 |
def main():
atgc = ["A", "T", "G", "C"]
mod = 10 ** 9 + 7
n = int(eval(input()))
dp = [[[[0 for i3 in range(4)] for i2 in range(4)] for i1 in range(4)] for i0 in range(n)]
for i in range(4):
for j in range(4):
for k in range(4):
dp[0][i][j][k] = 1
dp[0][0][2][3] = 0
dp[0][0][3][2] = 0
dp[0][2][0][3] = 0
for t in range(n-3):
for i in range(4):
for j in range(4):
for k in range(4):
dp[t+1][i][j][k] = dp[t][0][i][j] + dp[t][1][i][j] + dp[t][2][i][j] + dp[t][3][i][j]
for i in range(4):
dp[t+1][i][2][3] -= dp[t][0][i][2]
for i in range(4):
dp[t+1][2][i][3] -= dp[t][0][2][i]
#AGG→GGC
dp[t + 1][2][2][3] += dp[t][0][2][2]
dp[t+1][0][2][3] = 0
dp[t+1][0][3][2] = 0
dp[t+1][2][0][3] = 0
ans = 0
for i in range(4):
for j in range(4):
for k in range(4):
ans += dp[n-3][i][j][k]
print((ans%mod))
main()
| import itertools
def main():
atgc = ["A", "T", "G", "C"]
mod = 10 ** 9 + 7
n = int(eval(input()))
dp = [[[[0 for i3 in range(4)] for i2 in range(4)] for i1 in range(4)] for i0 in range(n)]
for i, j, k in itertools.product(list(range(4)), list(range(4)), list(range(4))):
dp[0][i][j][k] = 1
dp[0][0][2][3] = 0 #AGC
dp[0][0][3][2] = 0 #ACG
dp[0][2][0][3] = 0 #GAC
for t in range(n-3):
for i, j, k in itertools.product(list(range(4)), list(range(4)), list(range(4))):
dp[t+1][i][j][k] = dp[t][0][i][j] + dp[t][1][i][j] + dp[t][2][i][j] + dp[t][3][i][j]
for i in range(4):
dp[t+1][i][2][3] -= dp[t][0][i][2] #(A)*GC
for i in range(4):
dp[t+1][2][i][3] -= dp[t][0][2][i] #(A)G*C
#(A)GGCが重複しているので
dp[t+1][2][2][3] += dp[t][0][2][2]
dp[t+1][0][2][3] = 0 #AGC
dp[t+1][0][3][2] = 0 #ACG
dp[t+1][2][0][3] = 0 #GAC
ans = 0
for i, j, k in itertools.product(list(range(4)), list(range(4)), list(range(4))):
ans += dp[n-3][i][j][k]
print((ans%mod))
main() | p03088 |
n = int(eval(input()))
ans = 0
hoges = []
seeds = 'ATCG'
def ng(currents):
v = 'AGC' in currents
# for k in range(max(1, 0), len(currents)):
for k in range(max(1, len(currents) - 3), len(currents)):
v = v or 'AGC' in (currents[:k-1] + currents[k] + currents[k-1] + currents[k+1:])
return v
memo = {}
ng_memo = {} # 後ろ4つだけ見ればNGわかる?
def f(index, currents):
ng_key = currents[-4:]
key = '%d:%s' % (index, currents[-4:])
# print(key)
if ng_key in ng_memo:
return 0
if key in memo:
return memo[key]
if ng(currents):
ng_memo[key] = True
return 0
if index == n:
return 1
memo[key] = sum([f(index+1, currents + s) for s in seeds])
return memo[key]
print((f(0, '') % int(1e9+7)))
# 3: 61
# 4: 230
# 5: 865
# 6: 3247
# 7: 12185
# 8: 45719
| n = int(eval(input()))
seeds = 'ATCG'
def ng(currents):
v = 'AGC' in currents
for k in range(max(1, len(currents) - 3), len(currents)): # 先頭の方はチェック済み
v = v or 'AGC' in (currents[:k-1] + currents[k] + currents[k-1] + currents[k+1:])
return v
memo = {} # 今の長さと最新4つだけメモする
def f(index, currents):
key = '%d:%s' % (index, currents[-4:])
if key not in memo:
if ng(currents):
memo[key] = 0
else:
memo[key] = 1 if index == n else sum([f(index+1, currents + s) for s in seeds])
return memo[key]
print((f(0, '') % int(1e9+7)))
| p03088 |
Mod = 10**9+7
p = ["XAGC", "XGAC", "XACG"] + ["AGCX", "GACX", "ACGX"] + ["AGXC", "AXGC"]
q = ["A", "G", "C", "T"]
f = []
for s in p:
for c in q:
f.append(s.replace("X",c))
r = ["AGC", "GAC", "ACG"]
d = {}
e = {}
for x in q:
for y in q:
for z in q:
s = x+y+z
if not s in r:
d[s] = 1
e[s] = 0
n = int(eval(input()))
for i in range(n-3):
for s in list(e.keys()):
for c in q:
t = s+c
if t in f:
continue
e[t[1:]] = (e[t[1:]]+d[s])%Mod
for s in list(e.keys()):
d[s] = e[s]
e[s] = 0
print((sum(d.values())%Mod)) | Mod = 10**9+7
f3 = ["AGC", "GAC", "ACG"]
f4 = ["AGAC","AGGC","AGCC","AGTC"] + ["AAGC","AGGC","ACGC","ATGC"]
q = ["A", "G", "C", "T"]
d = {}
e = {}
for x in q:
for y in q:
for z in q:
s = x+y+z
if not s in f3:
d[s] = 1
e[s] = 0
n = int(eval(input()))
for i in range(n-3):
for s in list(e.keys()):
for c in q:
t = s+c
if t[1:] in f3 or t in f4:
continue
e[t[1:]] = (e[t[1:]]+d[s])%Mod
for s in list(e.keys()):
d[s] = e[s]
e[s] = 0
print((sum(d.values())%Mod))
| p03088 |
N = int(input().strip())
M = pow(10, 9) + 7
a = 1
g = 1
ag = 0
agg = 0
agt = 0
atg = 0
ac = 0
at = 0
aa = 0
ga = 0
al = 4
nal = 0
for i in range(N-1):
nal = (al * 4) % M
nal = (nal + M - (ag + ac + ga + agg + agt + atg) ) % M
agg = ag
agt = ag
atg = at
ag = a
aa = a
at = a
nac = (a + M- ga) % M
ga = g
a = al
g = (al + M - ac) % M
ac = nac
al = nal
print(al)
| a,g,a_,a__,ac,ga,al=[0]*6+[1]
for i in range(int(eval(input()))):
a__,a_,ac,ga,a,g,al=a_,a,a-ga,g,al,al-ac,(al*4-(a_+ac+ga+a__*3))%(pow(10,9)+7)
print(al)
| p03088 |
n, mod = int(eval(input())), 10 ** 9 + 7
memo = [{} for i in range(n+1)]
def check(l):
for i in range(4):
t = list(l)
if i >= 1:
t[i-1], t[i] = t[i], t[i-1] # 順序の入れ替え
if ''.join(t).count('AGC') >= 1:
return False
return True
def dfs(cur, last3):
if last3 in memo[cur]:
return memo[cur][last3]
if cur == n:
return 1
ret = 0
for c in 'ACGT':
if check(last3 + c):
ret = (ret + dfs(cur + 1, last3[1:] + c)) % mod
memo[cur][last3] = ret
return ret
print((dfs(0, 'TTT')))
| """
n, mod = int(input()), 10 ** 9 + 7
memo = [{} for i in range(n+1)]
def check(l):
for i in range(4):
t = list(l)
if i >= 1:
t[i-1], t[i] = t[i], t[i-1] # 順序の入れ替え
if ''.join(t).count('AGC') >= 1:
return False
return True
def dfs(cur, last3):
if last3 in memo[cur]:
return memo[cur][last3]
if cur == n:
return 1
ret = 0
for c in 'ACGT':
if check(last3 + c):
ret = (ret + dfs(cur + 1, last3[1:] + c)) % mod
memo[cur][last3] = ret
print(cur, memo)
return ret
print(dfs(0, 'TTT'))
"""
n, mod = int(eval(input())), 10 ** 9 + 7
memo = [[[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)] for _ in range(n + 1)]
memo[0][3][3][3] = 1
for length in range(n):
for s3 in range(4): # 一番最後の文字
for s2 in range(4): # 最後から2番目の文字
for s1 in range(4): # 最後から3番目の文字
# if memo[length][s3][s2][s1] == 0: continue
# 新しく追加する文字
for s4 in range(4):
# ダメな条件の時はcontinue
if s4 == 2 and s3 == 1 and s2 == 0: continue
if s4 == 2 and s3 == 0 and s2 == 1: continue
if s4 == 1 and s3 == 2 and s2 == 0: continue
if s4 == 2 and s3 == 1 and s1 == 0: continue
if s4 == 2 and s2 == 1 and s1 == 0: continue
memo[length + 1][s4][s3][s2] += memo[length][s3][s2][s1]
memo[length + 1][s4][s3][s2] %= mod
ans = 0
for i in range(4):
for j in range(4):
for k in range(4):
ans += memo[n][i][j][k]
ans %= mod
print(ans)
| p03088 |
import sys
from collections import defaultdict
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
N = int(readline())
dp = [defaultdict(int) for _ in range(N)]
for c in 'ACGT':
dp[0][c + 'XX'] = 1
for i in range(1, N):
for s, v in list(dp[i - 1].items()):
for c in 'AT':
dp[i][c + s[:2]] = (dp[i][c + s[:2]] + v) % MOD
if not (s[1] == 'A' and s[0] == 'C'):
dp[i]['G' + s[:2]] = (dp[i]['G' + s[:2]] + v) % MOD
if (
not (s[1] == 'A' and s[0] == 'G')
and not (s[1] == 'G' and s[0] == 'A')
and not (s[2] == 'A' and s[1] == 'G')
and not (s[2] == 'A' and s[0] == 'G')
):
dp[i]['C' + s[:2]] = (dp[i]['C' + s[:2]] + v) % MOD
ans = sum(dp[N - 1].values()) % MOD
print(ans)
return
if __name__ == '__main__':
main()
| import sys
from collections import defaultdict
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
N = int(readline())
dp = [defaultdict(int) for _ in range(N)]
for c in 'ACGT':
dp[0][c + 'XX'] = 1
for i in range(1, N):
for s, v in list(dp[i - 1].items()):
t = s[:2]
for c in 'AT':
dp[i][c + t] = (dp[i][c + t] + v) % MOD
if not (s[1] == 'A' and s[0] == 'C'):
dp[i]['G' + t] = (dp[i]['G' + t] + v) % MOD
if (
not (s[1] == 'A' and s[0] == 'G')
and not (s[1] == 'G' and s[0] == 'A')
and not (s[2] == 'A' and s[1] == 'G')
and not (s[2] == 'A' and s[0] == 'G')
):
dp[i]['C' + t] = (dp[i]['C' + t] + v) % MOD
ans = sum(dp[N - 1].values()) % MOD
print(ans)
return
if __name__ == '__main__':
main()
| p03088 |
import sys
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 6)
import math
from collections import Counter
from collections import deque
from operator import itemgetter
import time, random
MOD = 10 ** 9 + 7
from itertools import permutations
def dfs(s):
if len(s) == N:
return 1
if (s[-2] == 'A' and s[-1] == 'G') or (s[-2] == 'G' and s[-1] == 'A'):
return dfs(s+'A') % MOD + dfs(s+'G') % MOD + dfs(s+'T') % MOD
elif s[-2] == 'A' and s[-1] == 'C':
return dfs(s+'A') % MOD + dfs(s+'C') % MOD + dfs(s+'T') % MOD
else:
return dfs(s+'A') % MOD + dfs(s+'C') % MOD + dfs(s+'G') % MOD + dfs(s+'T') % MOD
def main():
N = int(readline())
A, G, C, T = 0, 1, 2, 3
dp = [[[[0] * 4 for _ in range(4)] for _ in range(4)] for _ in range(N+1)]
for j in range(4): # i - 2 文字目
for k in range(4): # i - 1 文字目
for l in range(4): # i 文字目
if j == A and k == G and l == C: continue
if j == A and k == C and l == G: continue
if j == G and k == A and l == C: continue
dp[3][j][k][l] = 1
for i in range(4, N+1):
for j in range(4):
for k in range(4):
for l in range(4):
for m in range(4):
if j == A and k == G and l == C: continue
if j == A and k == C and l == G: continue
if j == G and k == A and l == C: continue
if m == A and k == G and l == C: continue
if m == A and j == G and l == C: continue
dp[i][j][k][l] += dp[i-1][m][j][k]
dp[i][j][k][l] %= MOD
res = 0
for j in range(4):
for k in range(4):
for l in range(4):
res += dp[N][j][k][l]
res %= MOD
print(res)
if __name__ == '__main__':
main() | import sys
readline = sys.stdin.readline
MOD = 10 ** 9 + 7
def main():
N = int(readline())
A, G, C, T = 0, 1, 2, 3
dp = [[[[0] * 4 for _ in range(4)] for _ in range(4)] for _ in range(N+1)]
for j in range(4): # i - 2 文字目
for k in range(4): # i - 1 文字目
for l in range(4): # i 文字目
if j == A and k == G and l == C: continue
if j == A and k == C and l == G: continue
if j == G and k == A and l == C: continue
dp[3][j][k][l] = 1
for i in range(4, N+1):
for j in range(4):
for k in range(4):
for l in range(4):
for m in range(4):
if j == A and k == G and l == C: continue
if j == A and k == C and l == G: continue
if j == G and k == A and l == C: continue
if m == A and k == G and l == C: continue
if m == A and j == G and l == C: continue
dp[i][j][k][l] += dp[i-1][m][j][k]
dp[i][j][k][l] %= MOD
res = 0
for j in range(4):
for k in range(4):
for l in range(4):
res += dp[N][j][k][l]
res %= MOD
print(res)
if __name__ == '__main__':
main() | p03088 |
n = int(eval(input()))
dp = [[0]*4 for i in range(n+1)]
mod = 10**9+7
dp[0][0] = dp[0][1] = dp[0][2] = dp[0][3] = 1
dp[1][0] = dp[1][1] = dp[1][2] = dp[1][3] = 4
for i in range(2,n):
for j in range(4):
dp[i][j] = sum(dp[i-1])%mod
dp[i][1] -= dp[i-2][0]
dp[i][2] -= (dp[i-2][0] + dp[i-2][1])
if i >= 3:
dp[i][2] -= 3*dp[i-3][0]
dp[i][1] += dp[i-3][1]
print((sum(dp[n-1])%mod)) | n = int(eval(input()))
mod = 10**9 + 7
a = [0]*n
c = [0]*n
g = [0]*n
t = [0]*n
a[0] = c[0] = g[0] = t[0] = 1
a[1] = c[1] = g[1] = t[1] = 4
a[2], c[2], g[2], t[2] = 16, 14, 15, 16
for i in range(3, n):
v = (a[i-1] + c[i-1] + g[i-1] + t[i-1]) % mod
a[i] = v
c[i] = (v - a[i-2] - g[i-2] - 3*a[i-3]) % mod
g[i] = (v - a[i-2] + g[i-3]) % mod
t[i] = v
print(((a[n-1] + c[n-1] + g[n-1] + t[n-1]) % mod)) | p03088 |
####################
####################
####################
####################
from heapq import*
i=input
for s in[0]*int(i()):
n,x,*y=int(i()),[]
for _ in'_'*n:
k,l,r=list(map(int,i().split()))
if l>=r:s+=r;x+=[[k,l-r]]
else:s+=l;y+=[[n-k,r-l]]*(k<n)
for x in x,y:
x.sort();h=[]
for k,d in x:
heappush(h,d)
if len(h)>k:heappop(h)
for d in h:s+=d
print(s) | ####################
####################
####################
####################
from heapq import*
i=input
for s in[0]*int(i()):
n,x,*y=int(i()),[]
for _ in'_'*n:
k,l,r=list(map(int,i().split()))
if l>=r:x+=[[k,l,r]]
else:y+=[[n-k,r,l]]
for x in x,y:
x.sort();h=[]
for k,l,r in x:
if k:s+=l;heappush(h,l-r)
else:s+=r
if len(h)>k:s-=heappop(h)
print(s) | p02610 |
from heapq import*
i=input
for s in[0]*int(i()):
n,x,*y=int(i()),[]
for _ in'_'*n:k,l,r=t=[*list(map(int,i().split()))];x+=[t]*(l>r);y+=[[n-k,r,l]]*(l<=r)
for x in x,y:
x.sort();h=[]
for k,l,r in x:
s+=r
if k:s+=l-r;heappush(h,l-r)
if len(h)>k:s-=heappop(h)
print(s) | from heapq import*
i=input
for s in[0]*int(i()):
n,*x=int(i()),[],[]
for _ in'_'*n:k,l,r=t=[*list(map(int,i().split()))];x[l>r]+=[[[n-k,r,l],t][l>r]]
for x in x:
h=[]
for k,l,r in sorted(x):heappush(h,l-r);s+=l-(k<len(h)and heappop(h))
print(s) | p02610 |
from collections import deque
from heapq import heappush, heappushpop
import sys
input = sys.stdin.readline
def calc(camels):
camels = deque(sorted(camels, key=lambda x: x[0]))
N = len(camels)
heap = []
while camels and camels[0][0] == 0:
camels.popleft()
for i in range(1, N+1):
while camels and camels[0][0] == i:
_, x = camels.popleft()
if len(heap) < i:
heappush(heap, x)
elif heap[0] < x:
heappushpop(heap, x)
for _, x in camels:
if len(heap) < N:
heappush(heap, x)
elif heap[0] < x:
heappushpop(heap, x)
return sum(heap)
T = int(eval(input()))
for _ in range(T):
N = int(eval(input()))
s = 0
ans = 0
first = []
second = []
for i in range(N):
K, L, R = list(map(int, input().split()))
if L >= R:
first.append((K, L - R))
ans += R
else:
second.append((N - K, R - L))
ans += L
ans += calc(first) + calc(second)
print(ans) | from heapq import heappush, heappop
import sys
input = sys.stdin.readline
def calc(camels, N):
camels.sort(key=lambda x: x[0])
heap = []
for i, x in camels:
heappush(heap, x)
if len(heap) > i:
heappop(heap)
return sum(heap)
T = int(eval(input()))
for _ in range(T):
N = int(eval(input()))
s = 0
ans = 0
first = []
second = []
for i in range(N):
K, L, R = list(map(int, input().split()))
if L >= R:
first.append((K, L - R))
ans += R
else:
second.append((N - K, R - L))
ans += L
ans += calc(first, N) + calc(second, N)
print(ans) | p02610 |
import heapq
T=int(eval(input()))
for _ in range(T):
N=int(eval(input()))
llist=[]
rlist=[]
base=0
for _ in range(N):
K,L,R=list(map(int,input().split()))
base+=min(L,R)
if L>R:
llist.append((K,L-R))
elif L<R:
rlist.append((N-K,R-L))
llist.sort()
rlist.sort()
#print(base)
#print(llist)
#print(rlist)
hq_left=[]
for i,l in llist:
heapq.heappush(hq_left,l)
if len(hq_left)>i:
heapq.heappop(hq_left)
hq_right=[]
for i,r in rlist:
heapq.heappush(hq_right,r)
if len(hq_right)>i:
heapq.heappop(hq_right)
answer=base
while hq_left:
answer+=heapq.heappop(hq_left)
while hq_right:
answer+=heapq.heappop(hq_right)
print(answer) | import heapq
T=int(eval(input()))
for _ in range(T):
N=int(eval(input()))
llist=[]
rlist=[]
base=0
for _ in range(N):
K,L,R=list(map(int,input().split()))
if L>R:
llist.append((K,L-R))
base+=R
elif L<R:
rlist.append((N-K,R-L))
base+=L
else:
base+=L
llist.sort()
rlist.sort()
#print(base)
#print(llist)
#print(rlist)
hq_left=[]
for i,l in llist:
heapq.heappush(hq_left,l)
if len(hq_left)>i:
heapq.heappop(hq_left)
hq_right=[]
for i,r in rlist:
heapq.heappush(hq_right,r)
if len(hq_right)>i:
heapq.heappop(hq_right)
answer=base
while hq_left:
answer+=heapq.heappop(hq_left)
while hq_right:
answer+=heapq.heappop(hq_right)
print(answer) | p02610 |
def main():
from collections import deque
import sys
input = sys.stdin.readline
T = int(eval(input()))
def res_1(lis,ans):
flag = [False] * (N)
for klr in lis:
x = klr[0]
for _ in range(N):
if x<0:
ans += klr[2]
break
if flag[x]:
x -= 1
else:
flag[x] = True
ans += klr[1]
break
return ans
def res_2(lis,ans):
flag = [False] * (N)
for klr in right:
x = klr[0] + 1
for _ in range(N):
if x>=N:
ans += klr[1]
break
if flag[x]:
x += 1
else:
flag[x] = True
ans += klr[2]
break
return ans
for _ in range(T):
N = int(eval(input()))
KLR = [list(map(int,input().split())) for _ in range(N)]
left = deque([])
right = deque([])
ans = 0
for K,L,R in KLR:
x = L - R
if x==0:
ans += L
elif x>0:
left.append([K-1,L,R,x])
else:
right.append([K-1,L,R,x])
left = sorted(left,key = lambda x:x[3],reverse = True)
right = sorted(right, key = lambda x:x[3])
ans = res_1(left,ans)
ans = res_2(right,ans)
print(ans)
main() | def main():
from collections import deque
import sys
input = sys.stdin.readline
from heapq import heapify,heappop,heappush
T = int(eval(input()))
for _ in range(T):
N = int(eval(input()))
KLR = [list(map(int,input().split())) for _ in range(N)]
left = deque([])
right = deque([])
ans = 0
for K,L,R in KLR:
x = L - R
if x==0:
ans += L
elif x>0:
left.append([K,L,R])
ans += R
else:
right.append([K+1,L,R])
ans += L
left = sorted(left)
right = sorted(right,reverse=True)
S = []
heapify(S)
x = 1
i = 0
length = len(left)
while x<=N:
while i<length:
klr = left[i]
if klr[0]==x:
heappush(S,klr[1]-klr[2])
i += 1
else:
break
y = len(S) - x
if y<=0:
x += 1
continue
else:
for _ in range(y):
heappop(S)
ans += sum(S)
S = []
heapify(S)
x = N+1
i = 0
length = len(right)
while x>=0:
while i<length:
klr = right[i]
if klr[0]==x:
heappush(S,klr[2]-klr[1])
i += 1
else:
break
y = len(S) + x - N - 1
if y<=0:
x -= 1
continue
else:
for _ in range(y):
heappop(S)
ans += sum(S)
print(ans)
main() | p02610 |
from heapq import *
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
class SegtreeMax():
def __init__(self, n):
self.inf = 10 ** 16
tree_width = 2
while tree_width < n:
tree_width *= 2
self.tree_width = tree_width
self.tree = [0] * (tree_width * 2 - 1)
def update(self, i, a):
seg_i = self.tree_width - 1 + i
self.tree[seg_i] = a
while seg_i != 0:
seg_i = (seg_i - 1) // 2
self.tree[seg_i] = max(self.tree[seg_i * 2 + 1], self.tree[seg_i * 2 + 2])
def element(self, i):
return self.tree[self.tree_width - 1 + i]
# [l,r)の最小値
def max(self, l, r, seg_i=0, segL=0, segR=-1):
if segR == -1: segR = self.tree_width
if r <= segL or segR <= l: return 0
if l <= segL and segR <= r: return self.tree[seg_i]
segM = (segL + segR) // 2
ret0 = self.max(l, r, seg_i * 2 + 1, segL, segM)
ret1 = self.max(l, r, seg_i * 2 + 2, segM, segR)
return max(ret0, ret1)
for _ in range(II()):
n=II()
hp=[]
hpr=[]
ans=0
for _ in range(n):
k,l,r=MI()
if r<l:heappush(hp,(r-l,l,r,k))
elif r>l:heappush(hpr,(-r+l,l,r,k))
else:ans+=r
st=SegtreeMax(n+5)
for i in range(n+1):st.update(i,i)
while hp:
d,l,r,k=heappop(hp)
i=st.max(0,k+1)
if i:
ans+=l
st.update(i,0)
else:
ans+=r
st=SegtreeMax(n+5)
for i in range(n+1):st.update(i,i)
while hpr:
d,l,r,k=heappop(hpr)
k=n-k
i=st.max(0,k+1)
if i:
ans+=r
st.update(i,0)
else:
ans+=l
print(ans)
| from heapq import *
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
class SegtreeMax():
def __init__(self, aa):
n=len(aa)
self.inf = 10 ** 16
tree_width = 2
while tree_width < n:
tree_width *= 2
self.tree_width = tree_width
self.tree = [0] * (tree_width * 2 - 1)
self.tree[self.tree_width-1:self.tree_width-1+len(aa)]=aa
for i in range(tree_width-2,-1,-1):
self.tree[i]=max(self.tree[i*2+1],self.tree[i*2+2])
def update(self, i, a):
seg_i = self.tree_width - 1 + i
self.tree[seg_i] = a
while seg_i != 0:
seg_i = (seg_i - 1) // 2
self.tree[seg_i] = max(self.tree[seg_i * 2 + 1], self.tree[seg_i * 2 + 2])
def element(self, i):
return self.tree[self.tree_width - 1 + i]
# [l,r)の最小値
def max(self, l, r, seg_i=0, segL=0, segR=-1):
if segR == -1: segR = self.tree_width
if r <= segL or segR <= l: return 0
if l <= segL and segR <= r: return self.tree[seg_i]
segM = (segL + segR) // 2
ret0 = self.max(l, r, seg_i * 2 + 1, segL, segM)
ret1 = self.max(l, r, seg_i * 2 + 2, segM, segR)
return max(ret0, ret1)
for _ in range(II()):
n=II()
hp=[]
hpr=[]
ans=0
for _ in range(n):
k,l,r=MI()
if r<l:heappush(hp,(r-l,l,r,k))
elif r>l:heappush(hpr,(-r+l,l,r,k))
else:ans+=r
st=SegtreeMax(list(range(n+5)))
for i in range(n+1):st.update(i,i)
while hp:
d,l,r,k=heappop(hp)
i=st.max(0,k+1)
if i:
ans+=l
st.update(i,0)
else:
ans+=r
st=SegtreeMax(list(range(n+5)))
for i in range(n+1):st.update(i,i)
while hpr:
d,l,r,k=heappop(hpr)
k=n-k
i=st.max(0,k+1)
if i:
ans+=r
st.update(i,0)
else:
ans+=l
print(ans)
| p02610 |
from heapq import *
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
class SegtreeMax():
def __init__(self, aa):
n=len(aa)
self.inf = 10 ** 16
tree_width = 2
while tree_width < n:
tree_width *= 2
self.tree_width = tree_width
self.tree = [0] * (tree_width * 2 - 1)
self.tree[self.tree_width-1:self.tree_width-1+len(aa)]=aa
for i in range(tree_width-2,-1,-1):
self.tree[i]=max(self.tree[i*2+1],self.tree[i*2+2])
def update(self, i, a):
seg_i = self.tree_width - 1 + i
self.tree[seg_i] = a
while seg_i != 0:
seg_i = (seg_i - 1) // 2
self.tree[seg_i] = max(self.tree[seg_i * 2 + 1], self.tree[seg_i * 2 + 2])
def element(self, i):
return self.tree[self.tree_width - 1 + i]
# [l,r)の最小値
def max(self, l, r, seg_i=0, segL=0, segR=-1):
if segR == -1: segR = self.tree_width
if r <= segL or segR <= l: return 0
if l <= segL and segR <= r: return self.tree[seg_i]
segM = (segL + segR) // 2
ret0 = self.max(l, r, seg_i * 2 + 1, segL, segM)
ret1 = self.max(l, r, seg_i * 2 + 2, segM, segR)
return max(ret0, ret1)
for _ in range(II()):
n=II()
hp=[]
hpr=[]
ans=0
for _ in range(n):
k,l,r=MI()
if r<l:heappush(hp,(r-l,l,r,k))
elif r>l:heappush(hpr,(-r+l,l,r,k))
else:ans+=r
st=SegtreeMax(list(range(n+5)))
for i in range(n+1):st.update(i,i)
while hp:
d,l,r,k=heappop(hp)
i=st.max(0,k+1)
if i:
ans+=l
st.update(i,0)
else:
ans+=r
st=SegtreeMax(list(range(n+5)))
for i in range(n+1):st.update(i,i)
while hpr:
d,l,r,k=heappop(hpr)
k=n-k
i=st.max(0,k+1)
if i:
ans+=r
st.update(i,0)
else:
ans+=l
print(ans)
| from heapq import *
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
for _ in range(II()):
n=II()
ff=[]
bb=[]
ans=0
for _ in range(n):
k,l,r=MI()
if l>r:ff.append((k,l,r))
elif l<r:bb.append((n-k,l,r))
else:ans+=r
ff.sort()
hp=[]
for i,(k,l,r) in enumerate(ff):
heappush(hp,l-r)
ans+=l
if i+1<len(ff) and ff[i+1][0]==k:continue
while len(hp)>k:
d=heappop(hp)
ans-=d
bb.sort()
hp = []
for i, (k, l, r) in enumerate(bb):
heappush(hp, r-l)
ans += r
if i + 1 < len(bb) and bb[i + 1][0] == k: continue
while len(hp) > k:
d = heappop(hp)
ans -= d
print(ans)
| p02610 |
from heapq import*
i=input
s=sorted
def f(x):
s,n,*h=0,len(x)
while n:
while x and x[-1][0]>=n:k,l,r=x.pop();heappush(h,(r-l,l,r))
if h:s+=heappop(h)[1]
n-=1
return s+sum(r for _,_,r in x+h)
for _ in'_'*int(i()):
n,x,*y=int(i()),[]
for _ in'_'*n:
k,l,r=list(map(int,i().split()))
if l>r:x+=(k,l,r),
else:y+=(n-k,r,l),
print((f(s(x))+f(s(y)))) | from heapq import*
i=input
s=sorted
def f(x):
s,n,*h=0,len(x)
while n:
while x and x[-1][0]>=n:k,l,r=x.pop();heappush(h,(r-l,l,r))
if h:s+=heappop(h)[1]
n-=1
return s+sum(r for*_,r in x+h)
for _ in'_'*int(i()):
n,x,*y=int(i()),[]
for _ in'_'*n:
k,l,r=list(map(int,i().split()))
if l>r:x+=(k,l,r),
else:y+=(n-k,r,l),
print((f(s(x))+f(s(y)))) | p02610 |
from heapq import*
i=input
def f(x):
x.sort();s,n,*h=0,len(x)
while n:
n-=1
while x and x[-1][0]>n:k,l,r=x.pop();heappush(h,(r-l,l,r))
if h:s+=heappop(h)[1]
return s+sum(r for*_,r in x+h)
for _ in'_'*int(i()):
n,x,*y=int(i()),[]
for _ in'_'*n:
k,l,r=list(map(int,i().split()))
if l>r:x+=(k,l,r),
else:y+=(n-k,r,l),
print((f(x)+f(y))) | from heapq import*
i=input
for _ in'_'*int(i()):
n,s,x,*y=int(i()),0,[]
for _ in'_'*n:
k,l,r=list(map(int,i().split()))
if l>r:x+=(k,l,r),
else:y+=(n-k,r,l),
for x in(x,y):
x.sort();n,*h=len(x),
while n:
n-=1
while x and x[-1][0]>n:k,l,r=x.pop();heappush(h,(r-l,l,r))
if h:s+=heappop(h)[1]
for*_,r in x+h:s+=r
print(s) | p02610 |
from heapq import*
i=input
for _ in'_'*int(i()):
n,s,x,*y=int(i()),0,[];exec('k,l,r=t=[*map(int,i().split())];x+=[t]*(l>r);y+=[(n-k,r,l)]*(l<=r);'*n)
for x in x,y:
x.sort();n,*h=len(x),
while n:
n-=1
while x and x[-1][0]>n:k,l,r=x.pop();heappush(h,(r-l,l,r))
if h:s+=heappop(h)[1]
for*_,r in x+h:s+=r
print(s) | from heapq import*
i=input
for _ in'_'*int(i()):
n,s,x,*y=int(i()),0,[]
for _ in'_'*n:k,l,r=t=[*list(map(int,i().split()))];x+=[t]*(l>r);y+=[[n-k,r,l]]*(l<=r)
for x in x,y:
x.sort();n,*h=len(x),
while n:
while[[n,0,0]]<x[-1:]:k,l,r=x.pop();heappush(h,(r-l,l,r))
if h:s+=heappop(h)[1]
n-=1
for*_,r in x+h:s+=r
print(s) | p02610 |
from heapq import*
i=input
for s in[0]*int(i()):
n,x,*y=int(i()),[]
for _ in'_'*n:k,l,r=t=[*list(map(int,i().split()))];x+=[t]*(l>r);y+=[[n-k,r,l]]*(l<=r)
for x in x,y:
x.sort();n,*h=len(x),
while h+x:
while[[n]]<x[-1:]:k,l,r=x.pop();heappush(h,(r-l,l,r))
if h:s+=heappop(h)[2-(n>0)]
n-=1
print(s) | from heapq import*
i=input
for s in[0]*int(i()):
n,x,*y=int(i()),[]
for _ in'_'*n:k,l,r=t=[*list(map(int,i().split()))];x+=[t]*(l>r);y+=[[n-k,r,l]]*(l<=r)
for x in x,y:
x.sort();n,*h=len(x),
while h or x:
while[[n]]<x[-1:]:k,l,r=x.pop();heappush(h,(r-l,l,r))
if h:s+=heappop(h)[~(n>0)]
n-=1
print(s) | p02610 |
from heapq import*
i=input
for s in[0]*int(i()):
n,x,*y=int(i()),[]
for _ in'_'*n:k,l,r=t=[*list(map(int,i().split()))];x+=[t]*(l>r);y+=[[n-k,r,l]]*(l<=r)
for x in x,y:
x.sort();n=len(x);h=[(0,0)]*n*2
while h:
while[[n]]<x[-1:]:k,l,r=x.pop();heappush(h,(r-l,l,r))
s+=heappop(h)[~(n>0)];n-=1
print(s) | from heapq import*
i=input
for s in[0]*int(i()):
n,x,*y=int(i()),[]
for _ in'_'*n:k,l,r=t=[*list(map(int,i().split()))];x+=[t]*(l>r);y+=[[n-k,r,l]]*(l<=r)
for x in x,y:
h=[]
for k,l,r in sorted(x):
s+=r
if k:s+=l-r;heappush(h,l-r)
if len(h)>k:s-=heappop(h)
print(s) | p02610 |
from heapq import*
i=input
for s in[0]*int(i()):
n,x,*y=int(i()),[]
for _ in'_'*n:k,l,r=t=[*list(map(int,i().split()))];x+=[t]*(l>r);y+=[[n-k,r,l]]*(l<=r)
for x in x,y:h=[];s+=sum(heappush(h,l-r)or l-(k<len(h)and heappop(h))for k,l,r in sorted(x))
print(s) | from heapq import*
i=input
for s in[0]*int(i()):
n,*x=int(i()),[],[]
for _ in'_'*n:k,l,r=t=[*list(map(int,i().split()))];x[l>r]+=[[n-k,r,l],t][l>r],
for x in x:
h=[]
for k,l,r in sorted(x):heappush(h,l-r);s+=l-(k<len(h)and heappop(h))
print(s) | p02610 |
# point update
# range query
class SegmentTreeNode:
def __init__(self, start, end, initial, merge):
# print("s", start, end)
self.start = start
self.end = end
self.width = end - start
self.merge = merge
self.initial = initial
if self.width > 1:
w2 = self.width // 2
self.left = SegmentTreeNode(start, start + w2, initial, merge)
self.right = SegmentTreeNode(start + w2, end, initial, merge)
self.value = self.merge(self.left.value, self.right.value)
else:
self.value = self.initial
def update(self, index, value):
if self.start <= index and index < self.end:
if self.width == 1:
self.value = value
else:
self.left.update(index, value)
self.right.update(index, value)
self.value = self.merge(self.left.value, self.right.value)
def pick(self, start, end):
if start <= self.start and self.end <= end:
return self.value
elif self.start < end and self.end > start:
# m = self.merge(self.left.pick(start, end), self.right.pick(start, end))
# print(start, end, m)
return self.merge(self.left.pick(start, end), self.right.pick(start, end))
else:
return self.initial
def to_list(self, items):
if self.width == 1:
items.append(self.value)
else:
self.left.to_list(items)
self.right.to_list(items)
class SegmentTree:
def __init__(self, n, *, merge, initial = None):
width = 1
while width < n:
width *= 2
self.root = SegmentTreeNode(0, width, initial, merge)
self.root.value = 0
self.capacity = width
def update(self, index, value):
self.root.update(index, value)
def pick(self, start, end):
return self.root.pick(start, end)
def to_list(self):
items = []
self.root.to_list(items)
return items
def merge(l, r):
if r[1]:
return r
else:
return l
import sys
T = int(eval(input()))
def calc(camels):
camels.sort()
count = len(camels)
st = SegmentTree(count, merge = merge, initial = (None, False))
for i in range(count):
st.update(i, (i, True))
for i in range(count + 1, st.capacity):
st.update(i, (i, False))
score = 0
train = [None] * N
for D, L, R, K in camels:
if K >= 0:
i, c = st.pick(0, min(K, count))
# print(st.to_list(), file = sys.stderr)
# print(L, R, K, i, c, file = sys.stderr)
if c:
# print("x", i, L, R, file = sys.stderr)
st.update(i, (i, False))
train[i] = (L, R)
score += L
else:
score += R
else:
score += R
# print(train, file = sys.stderr)
return score
for t in range(T):
# print(f"t = {t}", file = sys.stderr)
N = int(eval(input()))
camels_l = []
camels_r = []
count_r = 0
for _ in range(N):
K, L, R = list(map(int, input().split()))
D = L - R
if D >= 0:
camels_l.append((-D, L, R, K))
else:
camels_r.append((D, R, L, N - K))
# print(camels_l)
# print(camels_r)
print((calc(camels_l) + calc(camels_r)))
| T = int(eval(input()))
import heapq
def calc(camels):
camels.sort()
camels.reverse()
count = len(camels)
score = 0
queue = []
i = 0
for k in range(count, 0, -1):
while i < count and camels[i][0] >= k:
K, L, R = camels[i]
heapq.heappush(queue, (-(L - R), L, R))
i += 1
if len(queue) > 0:
D, L, R = heapq.heappop(queue)
score += L
while len(queue) > 0:
D, L, R = heapq.heappop(queue)
score += R
while i < count:
K, L, R = camels[i]
score += R
i += 1
return score
for t in range(T):
N = int(eval(input()))
camels_l = []
camels_r = []
count_r = 0
for _ in range(N):
K, L, R = list(map(int, input().split()))
if L - R >= 0:
camels_l.append((K, L, R))
else:
camels_r.append((N - K, R, L))
print((calc(camels_l) + calc(camels_r)))
| p02610 |
import sys
from heapq import heappush, heappop
readline = sys.stdin.readline
def solve():
N = int(readline())
left = [[] for _ in range(N)]
right = [[] for _ in range(N)]
ans = 0
for _ in range(N):
K, L, R = list(map(int, readline().split()))
if L > R:
ans += R
left[K - 1].append(R - L)
else:
ans += L
if 0 <= N - K - 1:
right[N - K - 1].append(L - R)
for vec in (left, right):
hq = []
n = len(vec)
for idx in range(N - 1, -1, -1):
for p in vec[idx]:
heappush(hq, p)
if idx < n and hq:
ans -= heappop(hq)
return ans
def main():
T = int(readline())
ans = [0] * T
for i in range(T):
ans[i] = solve()
print(('\n'.join(map(str, ans))))
return
if __name__ == '__main__':
main()
| import sys
from heapq import heappush, heappop
readline = sys.stdin.readline
def solve():
N = int(readline())
left = [[] for _ in range(N)]
right = [[] for _ in range(N)]
ans = 0
for _ in range(N):
K, L, R = list(map(int, readline().split()))
if L > R:
ans += R
left[K - 1].append(L - R)
else:
ans += L
if 0 <= N - K - 1:
right[N - K - 1].append(R - L)
for vec in (left, right):
hq = []
n = len(vec)
for idx in range(N):
for p in vec[idx]:
heappush(hq, p)
while len(hq) > min(idx + 1, n):
heappop(hq)
ans += sum(hq)
return ans
def main():
T = int(readline())
ans = [0] * T
for i in range(T):
ans[i] = solve()
print(('\n'.join(map(str, ans))))
return
if __name__ == '__main__':
main()
| p02610 |
import sys
from heapq import heappush, heappop
readline = sys.stdin.readline
def solve():
N = int(readline())
left = [[] for _ in range(N)]
right = [[] for _ in range(N)]
ans = 0
for _ in range(N):
K, L, R = list(map(int, readline().split()))
if L > R:
ans += R
left[K - 1].append(L - R)
else:
ans += L
if 0 <= N - K - 1:
right[N - K - 1].append(R - L)
for vec in (left, right):
hq = []
n = len(vec)
for idx in range(N):
for p in vec[idx]:
heappush(hq, p)
while len(hq) > min(idx + 1, n):
heappop(hq)
ans += sum(hq)
return ans
def main():
T = int(readline())
ans = [0] * T
for i in range(T):
ans[i] = solve()
print(('\n'.join(map(str, ans))))
return
if __name__ == '__main__':
main()
| import sys
from heapq import heappush, heappop
readline = sys.stdin.readline
def solve():
N = int(readline())
left = [[] for _ in range(N)]
right = [[] for _ in range(N)]
ans = 0
for _ in range(N):
K, L, R = list(map(int, readline().split()))
if L > R:
ans += R
left[K - 1].append(L - R)
else:
ans += L
if 0 <= N - K - 1:
right[N - K - 1].append(R - L)
for vec in (left, right):
hq = []
n = len(vec)
for i in range(n):
for p in vec[i]:
heappush(hq, p)
while len(hq) > i + 1:
heappop(hq)
for i in range(n, N):
for p in vec[i]:
heappush(hq, p)
while len(hq) > n:
heappop(hq)
ans += sum(hq)
return ans
def main():
T = int(readline())
ans = [0] * T
for i in range(T):
ans[i] = solve()
print(('\n'.join(map(str, ans))))
return
if __name__ == '__main__':
main()
| p02610 |
n = eval(input())
numbers = input().split()
print((' '.join(numbers[::-1]))) | n = eval(input())
numbers = list(input().split())
print((" ".join(numbers[::-1]))) | p02407 |
input()
i = list(map(int, input().split()))
i.reverse()
for j in range(len(i)) :
if j != 0 :
print(' ', end = '')
print(i[j], end = '')
print()
| eval(input())
data = input().split()
data.reverse()
print((' '.join(data))) | p02407 |
eval(input())
a = list(input().split())
a.reverse()
print((" ".join(a))) | eval(input())
print((" ".join(reversed(input().split())))) | p02407 |
import sys
n = int( sys.stdin.readline() )
nums = sys.stdin.readline().rstrip().split( " " )
nums.reverse()
output = []
for i in range( n ):
output.append( nums[i] )
if i < (n-1):
output.append( " " )
print(( "".join( output ) )) | import sys
n = int( sys.stdin.readline() )
nums = sys.stdin.readline().rstrip().split( " " )
nums.reverse()
print(( " ".join( nums ) )) | p02407 |
n = int(input())
a = list(map(int,input().split()))
a.reverse()
for i in range(n-1):
print(a[i],end = " ")
print(a[n-1])
| n =int(input())
a = list(map(int,input().split()))
a.reverse()
for i in range(n):
if i!=n-1:
print(a[i],end=" ")
else:
print(a[i])
| p02407 |
n = int(input())
ls = list(map(int,input().split()))
print(' '.join(map(str,ls[::-1]))) | n = int(input())
print(' '.join(input().split()[::-1])) | p02407 |
#coding:utf-8
#1_6_A 2015.4.1
n = int(input())
numbers = list(map(int,input().split()))
for i in range(n):
if i == n - 1:
print(numbers[-i-1])
else:
print(numbers[-i-1], end = ' ')
| #coding:utf-8
#1_6_A 2015.4.1
eval(input())
numbers = input().split()
numbers.reverse()
print((' '.join(numbers))) | p02407 |
n,k = list(map(int,input().split()))
pList = list(map(int,input().split()))
cList = list(map(int,input().split()))
cSum = sum(cList)
p = dict()
c = dict()
for i in range(n):
p[i] = pList[i]
c[i] = cList[i]
highScore = min(cList)
for i in range(n):
count = 0
zahyou = i
score = 0
zumi =set()
loop = False
while count < k:
if not(loop):
if zahyou in zumi:
loop = True
if score > 0:
score += score * ((k // count) - 2)
count += ((k // count) - 2) * count
else:
break
zumi.add(zahyou)
zahyou = p[zahyou] - 1
score += c[zahyou]
count += 1
if highScore < score:
highScore = score
print(highScore) | n,k = list(map(int,input().split()))
pList = list(map(int,input().split()))
cList = list(map(int,input().split()))
cSum = sum(cList)
p = dict()
c = dict()
for i in range(n):
p[i] = pList[i]
c[i] = cList[i]
highScore = min(cList)
for i in range(n):
count = 0
zahyou = i
score = 0
zumi =zahyou
loop = False
while count < k:
if not(loop):
if zahyou == zumi and count != 0:
loop = True
if score > 0:
score += score * ((k // count) - 2)
count += ((k // count) - 2) * count
else:
break
zahyou = p[zahyou] - 1
score += c[zahyou]
count += 1
if highScore < score:
highScore = score
print(highScore) | p02585 |
import sys
import copy
input = sys.stdin.readline
N,K=list(map(int,input().split()))
P=list(map(int,input().split()))
C=list(map(int,input().split()))
ans=-1*(10**10)
for i in range(N):
tmp=0
pos=i
count=0
while count<K:
#print(pos,P[pos])
tmp+=C[P[pos]-1]
if tmp>ans:
ans=tmp
pos=P[pos]-1
count+=1
print(ans) | import sys
import copy
input = sys.stdin.readline
N,K=list(map(int,input().split()))
P=list(map(int,input().split()))
C=list(map(int,input().split()))
ans=-1*(10**10)
if K<10000000:
for i in range(N):
tmp=0
pos=i
count=0
while count<K:
#print(pos,P[pos])
tmp+=C[P[pos]-1]
if tmp>ans:
ans=tmp
pos=P[pos]-1
count+=1
print(ans)
else:
for i in range(N):
tmp=0
pos=i
gpos=i
count=0
while count<K:
#print(pos,P[pos])
tmp+=C[P[pos]-1]
if tmp>ans:
ans=tmp
pos=P[pos]-1
count+=1
if pos==gpos:
divide=K//count-1
tmp=tmp*divide
count=count*divide
gpos=10**10
print(ans) | p02585 |
N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
C = list(map(int, input().split()))
INF = 10**9+1
def solve():
cycles = []
memo = [False] * N
i = 0
while i < N-1:
cycle = []
j = i
while not memo[j]:
cycle.append(j)
memo[j] = True
j = P[j] - 1
k = i
for i in range(k, N):
if not memo[i]:
break
cycles.append(cycle)
ans = -INF
for cycle in cycles:
n = len(cycle)
# q, r = divmod(K-1, n)
# r += 1
memo = [-INF] * n
for i in range(n):
s = 0
for j in range(n):
s += C[cycle[(i+j)%n]]
memo[j] = max(memo[j], s)
tmpmax = -INF
imax = -1
if K < n:
for i in range(K):
if tmpmax < memo[i]:
tmpmax = memo[i]
imax = i+1
else:
if memo[-1] > 0:
for i in range(n):
q = (K-i-1) // n
tmpmax = max(tmpmax, memo[i] + memo[-1] * q)
else:
for i in range(n):
tmpmax = max(tmpmax, memo[i])
ans = max(ans, tmpmax)
return ans
if __name__ == "__main__":
print((solve()))
| N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
C = list(map(int, input().split()))
INF = 10**9+1
def solve():
ans = -INF
for i in range(N):
memo = [0] * (N+1)
j = 0
p = i
while j < N:
memo[j+1] = memo[j] + C[p]
p = P[p] - 1
j += 1
if p == i:
break
tans =-INF
if memo[j] > 0:
for k in range(j):
q = (K-k-1) // j
tans = max(tans, memo[k+1] + memo[j] * q)
else:
for k in range(min(K, j)):
tans = max(tans, memo[k+1])
ans = max(ans, tans)
return ans
if __name__ == "__main__":
print((solve()))
| p02585 |
N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
P = [p - 1 for p in P]
C = list(map(int, input().split()))
vis = [False] * N
ans = [-float('inf')] * N
for root in range(N):
if vis[root]:
continue
vis[root] = True
cycle = [root]
costs = [C[root]]
u = P[root]
while u != root:
cycle.append(u)
costs.append(C[u])
u = P[u]
# print('-' * 10)
# print(cycle)
# print(costs)
L = len(cycle)
S = sum(costs)
for i, v in enumerate(cycle):
cnt = 0
for step in range(1, min(L, K) + 1):
cnt += costs[(i + step) % L]
val1 = cnt
val2 = cnt + (K - step) // L * S
ans[v] = max(ans[v], val1, val2)
print((max(ans)))
| N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
P = [p - 1 for p in P]
C = list(map(int, input().split()))
vis = [False] * N
ans = [-float('inf')] * N
for root in range(N):
if vis[root]:
continue
vis[root] = True
cycle = [root]
costs = [C[root]]
u = P[root]
vis[u] = True
while u != root:
cycle.append(u)
costs.append(C[u])
u = P[u]
vis[u] = True
# print('-' * 10)
# print(cycle)
# print(costs)
L = len(cycle)
S = sum(costs)
for i, v in enumerate(cycle):
cnt = 0
for step in range(1, min(L, K) + 1):
cnt += costs[(i + step) % L]
val1 = cnt
val2 = cnt + (K - step) // L * S
ans[v] = max(ans[v], val1, val2)
print((max(ans)))
| p02585 |
N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
P = [p - 1 for p in P]
C = list(map(int, input().split()))
vis = [False] * N
ans = [-float('inf')] * N
for root in range(N):
if vis[root]:
continue
cycle = [root]
costs = [C[root]]
u = P[root]
while u != root:
cycle.append(u)
costs.append(C[u])
u = P[u]
for u in cycle:
vis[u] = True
L = len(cycle)
S = sum(costs)
for i, v in enumerate(cycle):
# Rewrite [1, K] as form q * L + r, :
# 0L + 1, 0L + 2, ..., 0L + L
# 1L + 1, 1L + 2, ..., 1L + L
# ⋮
# tL + 1, tL + 2, ... (t = floor((K - r) / L))
# We can ignore 1L + r, 2L + r, ..., (t - 1) * L + r
# since the total cost of loop is either positive or negative
# When positive, 0L + r < 1L + r < 2L + r < tL + r
# When negative, the answer should be 0L + r
cnt = 0
for rem in range(1, min(L, K) + 1):
cnt += costs[(i + rem) % L]
val1 = cnt
val2 = cnt + (K - rem) // L * S
ans[v] = max(ans[v], val1, val2)
print((max(ans)))
| N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
P = [p - 1 for p in P]
C = list(map(int, input().split()))
vis = [False] * N
ans = [-float('inf')] * N
for root in range(N):
if vis[root]:
continue
cycle = [root]
costs = [C[root]]
u = P[root]
while u != root:
cycle.append(u)
costs.append(C[u])
u = P[u]
for u in cycle:
vis[u] = True
L = len(cycle)
S = sum(costs)
for i, v in enumerate(cycle):
# Rewrite [1, K] as form q * L + r,
# 0L + 1, 0L + 2, ..., 0L + L
# 1L + 1, 1L + 2, ..., 1L + L
# ⋮
# tL + 1, tL + 2, ...
# We can ignore 1L + r, 2L + r, ..., (t - 1) * L + r
# since the total cost of loop is either > 0 or <= 0
# When > 0, 0L + r < 1L + r < 2L + r < tL + r
# When <= 0, the answer should be 0L + r
if S > 0:
rem_cost = 0
for rem in range(1, min(L, K) + 1):
rem_cost += costs[(i + rem) % L]
t = (K - rem) // L
ans[v] = max(ans[v], rem_cost + t * S)
else:
rem_cost = 0
for rem in range(1, min(L, K) + 1):
rem_cost += costs[(i + rem) % L]
ans[v] = max(ans[v], rem_cost)
print((max(ans)))
| p02585 |
import sys
from collections import deque
N, K = list(map(int, sys.stdin.readline().split()))
P = list(map(int, sys.stdin.readline().split()))
C = list(map(int, sys.stdin.readline().split()))
# 重み付き有向グラフ
# edges = [[] for _ in range(N)]
# for i in range(N):
# edges[i].append((P[i]-1, C[i]))
# DFSで閉路と経路の最大取得スコアを調査
ans = -float("inf")
for i in range(N):
q = deque([(i, 0, 0)])
cycle_score = -1
cycle_count = -1
cycle_start = None
scores = {} # (score, count)
while q:
node1, score, count = q.popleft()
# print(node1, score, count)
if K < count:
break
if 0 < count:
ans = max(ans, score)
if node1 in scores:
# 閉路
if score > 0:
# print("plus cycle detected")
# cycle.add((score, count, i))
cycle_score = score
cycle_count = count
cycle_start = node1
break
scores[node1] = (score, count)
# for で回しているが、実際は一択
# for node2, weight in edges[node1]:
# q.appendleft((node2, score + weight, count + 1))
node2 = P[node1] - 1
weight = C[node2]
q.append((node2, score + weight, count + 1))
# cycleを回れる限界の-1から始めて、最大のスコアを算出
if cycle_start is not None:
cycle_len = cycle_count - scores[cycle_start][1]
# print("cycle_len", cycle_len, "cycle_score", cycle_score - scores[cycle_start][0])
loop = (K - scores[cycle_start][1]) // cycle_len - 1
count = loop * cycle_len + scores[cycle_start][1]
score = scores[cycle_start][0] + loop * (cycle_score - scores[cycle_start][0])
# print(count, score, loop)
q = deque([(cycle_start, score, count)])
while q:
node1, score, count = q.popleft()
# print(node1, score, count)
if count > K:
break
ans = max(ans, score)
# for node2, weight in edges[node1]:
# q.appendleft((node2, score + weight, count + 1))
node2 = P[node1] - 1
weight = C[node2]
q.append((node2, score + weight, count + 1))
print(ans) | import sys
input = sys.stdin.readline
N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
C = list(map(int, input().split()))
ans = -float('inf')
for s in range(N):
S = []
i = P[s] - 1
S.append(C[i])
while i != s:
i = P[i] - 1
S.append(S[-1] + C[i])
if K <= len(S):
tmp = max(S[:K])
elif S[-1] <= 0:
tmp = max(S)
else:
# ループの中で最大となるところで止める
tmp1 = S[-1] * (K // len(S) - 1)
tmp1 += max(S)
# 限界まで進む
tmp2 = S[-1] * (K // len(S))
r = K % len(S)
if r != 0:
tmp2 += max(0, max(S[:r]))
tmp = max(tmp1, tmp2)
ans = max(ans, tmp)
print(ans) | p02585 |
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
# map(int, input().split())
N, K = list(map(int, input().split()))
P = list([int(x) - 1 for x in input().split()])
C = list(map(int, input().split()))
ans = -INF
for i in range(N):
nx = i
total = 0
L = []
while True:
nx = P[nx]
total += C[nx]
L.append(C[nx])
if nx == i:
break
l = len(L)
now = 0
for j in range(l):
if j + 1 > K:
break
now += L[j]
ans = max(ans, now)
if total > 0:
now = total * (K // l)
ans = max(ans, now)
r = K % l
for j in range(r):
now += L[j]
ans = max(ans, now)
print(ans)
| import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
# map(int, input().split())
N, K = list(map(int, input().split()))
P = list([int(x) - 1 for x in input().split()])
C = list(map(int, input().split()))
ans = -INF
for i in range(N):
nx = i
total = 0
L = []
while True:
nx = P[nx]
total += C[nx]
L.append(C[nx])
if nx == i:
break
l = len(L)
tmp = 0
for j in range(l):
if j + 1 > K:
break
tmp += L[j]
now = tmp
if total > 0:
e = (K - j - 1) // l
now += total * e
ans = max(ans, now)
# if total > 0:
# now = total * (K // l)
# ans = max(ans, now)
# r = K % l
# for j in range(r):
# now += L[j]
# ans = max(ans, now)
print(ans)
| p02585 |
def main():
from sys import setrecursionlimit, stdin, stderr
from os import environ
from collections import defaultdict, deque, Counter
from math import ceil, floor
from itertools import accumulate, combinations, combinations_with_replacement
setrecursionlimit(10**6)
dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
input = lambda: stdin.readline().rstrip()
LMIIS = lambda: list(map(int,input().split()))
II = lambda: int(eval(input()))
P = 10**9+7
INF = 10**18+10
N,K = LMIIS()
P = list([int(x)-1 for x in input().split()])
C = LMIIS()
score_sets = []
used = [False]*N
tmp = P[0]
for i in range(N):
if not used[i]:
tmp = i
score_set = []
while not used[tmp]:
used[tmp] = True
tmp = P[tmp]
score_set.append(C[tmp])
score_sets.append(score_set)
ans = -INF
for score_set in score_sets:
# 合計が最大になる区間を探す
tmp_max = -INF
base_cum = 0
sum_score_set = sum(score_set)
remain_K = K
if sum_score_set > 0:
num = max(0,K//len(score_set)-1)
base_cum = sum_score_set * num
remain_K -= num*len(score_set)
for i in range(len(score_set)):
cum = base_cum
for j in range(i,i+remain_K):
cum += score_set[j%len(score_set)]
tmp_max = max(tmp_max,cum)
ans = max(ans,tmp_max)
print(ans)
main() | def main():
from sys import setrecursionlimit, stdin, stderr
from os import environ
from collections import defaultdict, deque, Counter
from math import ceil, floor
from itertools import accumulate, combinations, combinations_with_replacement
setrecursionlimit(10**6)
dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
input = lambda: stdin.readline().rstrip()
LMIIS = lambda: list(map(int,input().split()))
II = lambda: int(eval(input()))
P = 10**9+7
INF = 10**18+10
N,K = LMIIS()
P = list([int(x)-1 for x in input().split()])
C = LMIIS()
score_sets = []
used = [False]*N
tmp = P[0]
for i in range(N):
if not used[i]:
tmp = i
score_set = []
while not used[tmp]:
used[tmp] = True
tmp = P[tmp]
score_set.append(C[tmp])
score_sets.append(score_set)
ans = -INF
for score_set in score_sets:
# 合計が最大になる区間を探す
len_set = len(score_set)
sum_score_set_real = sum(score_set)
sum_score_set = max(0,sum_score_set_real)
for i in range(len_set):
cum_sum_1 = 0
for j in range(i,min(len_set, i+K)):
cum_sum_1 += score_set[j]
num_move = j-i+1
tmp_max = cum_sum_1 + (K - num_move) // len_set * sum_score_set
ans = max(ans, tmp_max)
for i in range(1,len_set-1):
cum_sum_2 = sum_score_set_real
for j in range(i,min(len_set-1-(K-i),len_set-1)):
cum_sum_2 -= score_set[j]
for j in range(min(max(i,len_set-1-(K-i)),len_set-1),len_set-1):
cum_sum_2 -= score_set[j]
num_move = len_set - (j-i+1)
tmp_max = cum_sum_2 + (K - num_move) // len_set * sum_score_set
ans = max(ans,tmp_max)
print(ans)
main() | p02585 |
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
from collections import deque, defaultdict
def main():
n, ko = list(map(int, input().split()))
p = tuple(map(int, input().split()))
c = tuple(map(int, input().split()))
scores_all = deque()
for k1 in range(n):
scores = deque()
kita = defaultdict(int)
kita[k1] = ko
cnt = ko - 1
koko = p[k1] - 1
scores.append(c[koko])
kita[koko] = cnt
while cnt:
cnt -= 1
koko = p[koko] - 1
scores.append(c[koko])
if kita[koko]:
break
else:
kita[koko] = cnt
cycle_long = kita[koko] - cnt
scores_a = tuple(accumulate(scores))
if cnt:
if scores_a[-1] > 0:
kaisuu = ko // cycle_long
s1 = scores_a[-1] * kaisuu
amari = ko % cycle_long
if amari:
t = max(0, max(scores_a[:amari]))
s1 += t
s2 = scores_a[-1] * (kaisuu - 1)
s2 += max(scores_a)
scores_all.append(max(s1, s2))
else:
scores_all.append(max(scores_a))
else:
scores_all.append(max(scores_a))
print((max(scores_all)))
if __name__ == '__main__':
main() | import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
def main():
n, k = list(map(int, input().split()))
p = tuple(map(int, input().split()))
c = tuple(map(int, input().split()))
if k == 1:
print((max(c)))
sys.exit()
seen = [0] * n
cycles = []
for i1 in range(n):
if not seen[i1]:
cycle_t = []
koko = i1
while True:
if seen[koko]:
cycles.append(cycle_t)
break
cycle_t.append(c[koko])
seen[koko] = 1
koko = p[koko] - 1
score = max(c)
for cycle in cycles:
score_t = max(cycle)
cycle_len = len(cycle)
cycle_sum = sum(cycle)
kaisu, rem = divmod(k, cycle_len)
if rem == 0:
kaisu -= 1
rem = cycle_len
if kaisu > 0:
kaisu -= 1
rem += cycle_len
cycle = tuple(accumulate(cycle + cycle + cycle))
for i1 in range(2, rem + 1):
for i2 in range(cycle_len):
score_t = max(score_t, cycle[i1+i2] - cycle[i2])
if cycle_sum > 0:
score_t += (kaisu * cycle_sum)
score = max(score, score_t)
print(score)
if __name__ == '__main__':
main()
| p02585 |
import sys
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline
def main():
N, K = [int(x) for x in input().split()]
P = [int(x) for x in input().split()]
C = [int(x) for x in input().split()]
ans = -float("inf")
for i in range(N):
next = P[i] - 1
cnt = 0
tmp = 0
f = False
while True:
tmp += C[next]
ans = max(ans, tmp)
cnt += 1
if next == i:
break
if cnt == K or next == i:
f = True
break
next = P[next] - 1
if f or tmp <= 0:
continue
q, r = divmod(K, cnt)
next = P[i] - 1
tmp *= q
cnt = 0
while True:
tmp += C[next]
ans = max(ans, tmp)
cnt += 1
if cnt == r:
break
next = P[next] - 1
print(ans)
if __name__ == '__main__':
main()
| import sys
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline
def main():
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()]
ans = max(C)
for i in range(N):
next = P[i]
cnt = 0
tmp = 0
while True:
tmp += C[next]
ans = max(ans, tmp)
cnt += 1
if cnt == K or next == i:
break
next = P[next]
if cnt == K or tmp <= 0:
continue
q = K // cnt
r = K % cnt
next = P[i]
if q != 0:
tmp *= (q - 1)
q -= 1
r += cnt
ans = max(ans, tmp)
else:
tmp = 0
while r > 0:
tmp += C[next]
ans = max(ans, tmp)
next = P[next]
r -= 1
print(ans)
if __name__ == '__main__':
main()
| p02585 |
N, K = list(map(int,input().split()))
P = [int(x)-1 for x in input().split()]
C = [int(x) for x in input().split()]
def loop(s):
value = 0
done = set()
while s not in done:
done.add(s)
s = P[s]
value += C[s]
return len(done), value
def f(s,K):
ans = -10**18
total = 0
done = set()
while s not in done:
done.add(s)
s = P[s]
total += C[s]
ans = max(ans,total)
K -= 1
if K==0:
return ans
lamb, value = loop(s)
if K > 2*lamb:
K -= lamb
if value > 0:
total += (K//lamb)*value
ans = max(ans,total)
K -= (K//lamb)*lamb
K += lamb
while K > 0:
s = P[s]
total += C[s]
ans = max(ans,total)
K -= 1
return ans
print((max([f(s,K) for s in range(N)]))) | N, K = list(map(int,input().split()))
P = [int(x)-1 for x in input().split()]
C = [int(x) for x in input().split()]
def loop(s):
value = 0
done = set()
while s not in done:
done.add(s)
s = P[s]
value += C[s]
return len(done), value
def f(s,K):
ans = -10**18
total = 0
done = set()
while s not in done:
done.add(s)
s = P[s]
total += C[s]
ans = max(ans,total)
K -= 1
if K==0:
return ans
lamb, value = loop(s)
if K > 2*lamb:
if value > 0:
K -= lamb
total += (K//lamb)*value
ans = max(ans,total)
K -= (K//lamb)*lamb
K += lamb
if value <= 0:
K = min(K,lamb+5)
while K > 0:
s = P[s]
total += C[s]
ans = max(ans,total)
K -= 1
return ans
print((max([f(s,K) for s in range(N)]))) | p02585 |
INF=10**9
f=lambda:[*list(map(int,input().split()))]
n,k=f()
p,c=f(),f()
p=[*[x-1 for x in p]]
tp=[[*list(range(n))] for _ in range(n+1)]
tc=[[0]*n for _ in range(n+1)]
lt=[0]*n
lc=[0]*n
for i in range(n):
for j in range(n):
t=p[tp[i][j]]
tp[i+1][j]=t
tc[i+1][j]=tc[i][j]+c[t]
if t==j and lt[j]==0:
lt[j]=i+1
lc[j]=tc[i+1][j]
a=-INF
for i in range(n):
if lc[i]<1 or k<=lt[i]:
for j in range(min(lt[i],k)):
a=max(a,tc[j+1][i])
else:
for j in range(lt[i]):
t=k//lt[i]*lc[i]+tc[j+1][i]
if k%lt[i]<j+1: t-=lc[i]
a=max(a,t)
print(a) | f=lambda:[*list(map(int,input().split()))]
n,k=f()
p,c=f(),f()
p=[*[x-1 for x in p]]
a=-10**9
for i in range(n):
x=i
l=[]
s=0
while 1:
x=p[x]
l+=[c[x]]
s+=c[x]
if x==i: break
m=len(l)
t=0
for j in range(m):
if j+1>k: break
t+=l[j]
a=max(a,t+(k-j-1)//m*s*(s>0))
print(a) | p02585 |
N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
C = list(map(int, input().split()))
P = [None] + P
C = [None] + C
all_max = C[1]
for st in range(1, N + 1):
scores = []
visit = set()
p = st
while p not in visit and len(visit) < K:
next_p = P[p]
scores.append(C[next_p])
visit.add(p)
p = next_p
num_elem = len(scores)
all_sum = sum(scores)
q, r = divmod(K, num_elem)
max_ = scores[0]
temp = scores[0]
max_r = scores[0]
temp_r = scores[0]
for x in range(1, num_elem):
if x < r:
temp_r += scores[x]
max_r = max(max_r, temp_r)
temp += scores[x]
max_ = max(max_, temp)
temp_max = scores[0]
if all_sum > 0 and q > 0:
if r > 0:
temp_max = max(all_sum * (q - 1) + max_, all_sum * q + max_r)
else:
temp_max = all_sum * (q - 1) + max_
else:
temp_max = max_
all_max = max(all_max, temp_max)
print(all_max)
| N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
C = list(map(int, input().split()))
P = [None] + P
C = [None] + C
all_max = C[1]
for st in range(1, N + 1):
p = P[st]
scores = [C[p]]
while p != st and len(scores) < K:
p = P[p]
scores.append(C[p])
num_elem = len(scores)
all_sum = sum(scores)
q, r = divmod(K, num_elem)
max_ = scores[0]
temp = scores[0]
max_r = scores[0]
temp_r = scores[0]
for x in range(1, num_elem):
if x < r:
temp_r += scores[x]
max_r = max(max_r, temp_r)
temp += scores[x]
max_ = max(max_, temp)
temp_max = scores[0]
if all_sum > 0 and q > 0:
if r > 0:
temp_max = max(all_sum * (q - 1) + max_, all_sum * q + max_r)
else:
temp_max = all_sum * (q - 1) + max_
else:
temp_max = max_
all_max = max(all_max, temp_max)
print(all_max)
| p02585 |
n,k = list(map(int,input().split()))
p = list(map(int,input().split()))
for i in range(n):
p[i] -= 1
c = list(map(int,input().split()))
reach = [False]*n
x = []
for i in range(n):
if reach[i]:continue
buf = []
cur = i
while not reach[cur]:
buf.append(c[cur])
reach[cur] = True
cur = p[cur]
x.append(buf)
ans = max(c)
import itertools
for i in x:
n = k//len(i)
ind = k%len(i)
if n>0:
n -= 1
ind += len(i)
else:
ind = min(k,len(i)*2)
ii = i+i+i
r = list(itertools.accumulate(ii))
a = max(0,r[len(i)-1]*n)
for j in range(len(i)):
for z in range(1,ind+1):
s = r[j+z]-r[j]
if z<ind+1:ans = max(ans,a+s)
else:ans = max(ans,s)
print(ans)
| n,k = list(map(int,input().split()))
p = list(map(int,input().split()))
for i in range(n):
p[i] -= 1
c = list(map(int,input().split()))
reach = [False]*n
x = []
for i in range(n):
if reach[i]:continue
buf = []
cur = i
while not reach[cur]:
buf.append(c[cur])
reach[cur] = True
cur = p[cur]
x.append(buf)
ans = max(c)
import itertools
for i in x:
n = k//len(i)
ind = k%len(i)
if n>0:
n -= 1
ind += len(i)
else:
ind = min(k,len(i)*2)
ii = i+i+i
r = list(itertools.accumulate(ii))
a = max(0,r[len(i)-1]*n)
for j in range(len(i)):
for z in range(1,ind+1):
s = r[j+z]-r[j]
ans = max(ans,a+s)
print(ans)
| p02585 |
n, k = list(map(int, input().split()))
p = [0] + list(map(int, input().split()))
c = [0] + list(map(int, input().split()))
ans = - 10 ** 18
for i in range(1, n+1):
base = i
nxt = p[i]
cnt = 0
score = 0
while True:
cnt += 1
if cnt > k:
break
score += c[nxt]
ans = max(ans, score)
#print("i = ", i, "ans = ", ans, "score = ", score)
if nxt == base:
break
nxt = p[nxt]
if cnt >= k:
continue
extra = k - cnt
score_tmp = score
nxt_tmp = nxt
nxt = p[nxt]
for j in range(extra):
score += c[nxt]
ans = max(ans, score)
#print("ans = ", ans, "score = ", score, "nxt = ", nxt, "c[nxt] = ", c[nxt])
nxt = p[nxt]
score = score_tmp
nxt = nxt_tmp
a = extra // cnt
score += score * a
ans = max(ans, score)
for j in range(extra - a * cnt):
score += c[nxt]
ans = max(ans, score)
nxt = p[nxt]
print(ans) | n, k = list(map(int, input().split()))
p = [0] + list(map(int, input().split()))
c = [0] + list(map(int, input().split()))
ans = - 10 ** 18
for i in range(1, n+1):
base = i
nxt = p[i]
cnt = 0
score = 0
while True:
cnt += 1
if cnt > k:
break
score += c[nxt]
ans = max(ans, score)
#print("i = ", i, "ans = ", ans, "score = ", score)
if nxt == base:
break
nxt = p[nxt]
if cnt >= k:
continue
extra = k - cnt
score_tmp = score
nxt = p[nxt]
nxt_tmp = nxt
for j in range(min(extra, cnt)):
score += c[nxt]
ans = max(ans, score)
#print("ans = ", ans, "score = ", score, "nxt = ", nxt, "c[nxt] = ", c[nxt])
nxt = p[nxt]
#print("score = ", score, "ans = ", ans)
score = score_tmp
nxt = nxt_tmp
a = extra // cnt
if extra % cnt == 0:
a -= 1
score += score * max(a, 0)
ans = max(ans, score)
for j in range(extra - a * cnt):
score += c[nxt]
ans = max(ans, score)
#print("ans = ", ans, "score = ", score, "nxt = ", nxt, "c[nxt] = ", c[nxt])
nxt = p[nxt]
print(ans) | p02585 |
n, k = list(map(int, input().split()))
p = list(map(int, input().split()))
c = list(map(int, input().split()))
mv_array = [set() for _ in range(n)]
score_mv_array = [[] for _ in range(n)]
score_array = [0]*n
def get_sum(array):
score_array = [0]
for i, a in enumerate(array):
score_array.append(score_array[i]+a)
return max(score_array)
def get_max(array, q, mod):
if q == 0:
m_score = get_sum(array[:mod])
else:
m_score = get_sum(array+array[:mod])
m_score = sum(array)*(q-1) + m_score
return m_score
for i in range(n):
score = 0
max_score = c[i]
pos = i
for j in range(k):
pos = p[pos]-1
if pos in mv_array[i]:
len_mv = len(score_mv_array[i])
q, mod = divmod(k-j, len_mv)
score += get_max(score_mv_array[i], q, mod)
max_score = max(score, max_score)
break
score += c[pos]
mv_array[i].add(pos)
score_mv_array[i].append(c[pos])
max_score = max(score, max_score)
score_array[i] = max_score
print((max(score_array))) | n, k = list(map(int, input().split()))
p = list(map(int, input().split()))
c = list(map(int, input().split()))
# mv_array = [set() for _ in range(n)]
score_mv_array = [[] for _ in range(n)]
score_array = [0]*n
def get_sum(array):
score_array = [0]
for i, a in enumerate(array):
score_array.append(score_array[i]+a)
return max(score_array)
def get_max(array, q, mod):
if q == 0:
m_score = get_sum(array[:mod])
else:
m_score = get_sum(array+array[:mod])
m_score = sum(array)*(q-1) + m_score
return m_score
for i in range(n):
score = 0
max_score = c[i]
pos = i
start_pos = p[pos]-1
for j in range(k):
pos = p[pos]-1
# if pos in mv_array[i]:
if j!=0 and pos == start_pos:
len_mv = len(score_mv_array[i])
q, mod = divmod(k-j, len_mv)
score += get_max(score_mv_array[i], q, mod)
max_score = max(score, max_score)
break
score += c[pos]
# mv_array[i].add(pos)
score_mv_array[i].append(c[pos])
max_score = max(score, max_score)
score_array[i] = max_score
print((max(score_array))) | p02585 |
n, k = list(map(int, input().split()))
p = list(map(int, input().split()))
c = list(map(int, input().split()))
# mv_array = [set() for _ in range(n)]
# score_mv_array = [[] for _ in range(n)]
score_array = [0]*n
def get_sum(array):
score_array = [0]
for i, a in enumerate(array):
score_array.append(score_array[i]+a)
return max(score_array)
def get_max(array, q, mod):
if q == 0:
m_score = get_sum(array[:mod])
else:
m_score = get_sum(array+array[:mod])
m_score = sum(array)*(q-1) + m_score
return m_score
for i in range(n):
score = 0
max_score = c[i]
score_mv_array = []
pos = i
start_pos = p[pos]-1
for j in range(k):
pos = p[pos]-1
if j!=0 and pos == start_pos:
# len_mv = len(score_mv_array)
len_mv = j
q, mod = divmod(k-j, len_mv)
score += get_max(score_mv_array, q, mod)
max_score = max(score, max_score)
break
score += c[pos]
score_mv_array.append(c[pos])
max_score = max(score, max_score)
score_array[i] = max_score
print((max(score_array))) | n, k = list(map(int, input().split()))
p = list(map(int, input().split()))
c = list(map(int, input().split()))
# mv_array = [set() for _ in range(n)]
# score_mv_array = [[] for _ in range(n)]
# score_array = [0]*n
def get_sum(array):
score_array = [0]
for i, a in enumerate(array):
score_array.append(score_array[i]+a)
return max(score_array)
def get_max(array, q, mod):
if q == 0:
m_score = get_sum(array[:mod])
else:
m_score = get_sum(array+array[:mod])
m_score = sum(array)*(q-1) + m_score
return m_score
max_score = -float('inf')
for i in range(n):
score = 0
# max_score = c[i]
score_mv_array = []
pos = i
start_pos = p[pos]-1
for j in range(k):
pos = p[pos]-1
if j!=0 and pos == start_pos:
# len_mv = len(score_mv_array)
len_mv = j
q, mod = divmod(k-j, len_mv)
score += get_max(score_mv_array, q, mod)
max_score = max(score, max_score)
break
score += c[pos]
score_mv_array.append(c[pos])
max_score = max(score, max_score)
# score_array[i] = max_score
# print(max(score_array))
print(max_score) | p02585 |
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
def main():
n,k = list(map(int,ipt().split()))
# n = 5000
# k = 1
p = [int(i)-1 for i in ipt().split()]
# p = [(i-1)%n for i in range(n)]
# c = [10**9 for i in range(n)]
c = [int(i) for i in ipt().split()]
ma = -10**18
al = [False]*n
for i in range(n):
if al[i]:
continue
pts = []
nap = i
for j in range(n):
nap = p[nap]
pts.append(c[nap])
al[nap] = True
if nap == i:
break
ln = len(pts)
jt = (k-1)%ln
jt += 1+ln
sma = 0
for jp in pts:
sma += jp
if sma > 0:
nm = ((k-1)//ln-1)*sma
else:
nm = 0
pts *= 2
ma1 = -10**18
# print(pts,al)
for ji in range(ln):
sm = 0
for jj in range(jt):
sm += pts[ji-jj]
# print(i,j,j-jj,sm)
if ma1 < sm:
ma1 = sm
ma1 += nm
if ma < ma1:
ma = ma1
# print(ma)
print(ma)
return None
if __name__ == '__main__':
main()
| '''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
def main():
n,k = list(map(int,ipt().split()))
# n = 5000
# k = 1
p = [int(i)-1 for i in ipt().split()]
# p = [(i-1)%n for i in range(n)]
# c = [10**9 for i in range(n)]
c = [int(i) for i in ipt().split()]
ma = -10**18
al = [False]*n
for i in range(n):
if al[i]:
continue
pts = []
nap = i
for j in range(n):
nap = p[nap]
pts.append(c[nap])
al[nap] = True
if nap == i:
break
ln = len(pts)
jt = k%ln+ln
sma = 0
for jp in pts:
sma += jp
if sma > 0:
nm = (k//ln-1)*sma
else:
nm = 0
pts *= 2
ma1 = -10**18
# print(pts,al)
for ji in range(ln):
sm = 0
for jj in range(jt):
sm += pts[ji-jj]
# print(i,j,j-jj,sm)
if ma1 < sm:
ma1 = sm
ma1 += nm
if ma < ma1:
ma = ma1
# print(ma)
print(ma)
return None
if __name__ == '__main__':
main()
| p02585 |
import copy
import math
import time
import statistics
import math
import itertools
import bisect
from decimal import *
# a = get_int()
def get_int():
return int(eval(input()))
# a = get_string()
def get_string():
return eval(input())
# a_list = get_int_list()
def get_int_list():
return [int(x) for x in input().split()]
# a_list = get_string_list():
def get_string_list():
return input().split()
# a, b = get_int_multi()
def get_int_multi():
return list(map(int, input().split()))
# a_list = get_string_char_list()
def get_string_char_list():
return list(str(eval(input())))
# print("{} {}".format(a, b))
# a_list = [0] * a
'''
while (idx < n) and ():
idx += 1
'''
def main():
start = time.time()
n, k = get_int_multi()
p = get_int_list()
c = get_int_list()
kaisuu = [-1] * n
score = [0] * n
for i in range(n):
wk = 0
ichi = i
for ii in range(n):
ichi = p[ichi] -1
wk += c[ichi]
if i == ichi:
kaisuu[i] = ii+1
score[i] = wk
break
wk = 0
ans = - 10 ** 20
for i in range(n):
ichi = p[i] -1
wk = c[ichi]
wk2 = c[ichi]
idx = 0
while idx < k-1:
ichi = p[ichi] -1
wk += c[ichi]
wk2 = max(wk2, wk)
idx += 1
#ループするならメモを使って減らす
if (k - 1 - idx > kaisuu[ichi] * 2) and kaisuu[ichi] > 0:
roopsuu = ((k - 1 - idx) // kaisuu[ichi]) -1
wk += roopsuu * score[ichi]
idx += roopsuu * kaisuu[ichi]
wk2 = max(wk2, wk)
ans = max(ans , wk2)
print(ans)
if __name__ == '__main__':
main()
| import copy
import math
import time
import statistics
import math
import itertools
import bisect
from decimal import *
# a = get_int()
def get_int():
return int(eval(input()))
# a = get_string()
def get_string():
return eval(input())
# a_list = get_int_list()
def get_int_list():
return [int(x) for x in input().split()]
# a_list = get_string_list():
def get_string_list():
return input().split()
# a, b = get_int_multi()
def get_int_multi():
return list(map(int, input().split()))
# a_list = get_string_char_list()
def get_string_char_list():
return list(str(eval(input())))
# print("{} {}".format(a, b))
# a_list = [0] * a
'''
while (idx < n) and ():
idx += 1
'''
def main():
start = time.time()
n, k = get_int_multi()
p = get_int_list()
c = get_int_list()
kaisuu = [-1] * n
score = [0] * n
score_max = [0] * n
for i in range(n):
wk = 0
wk2 = 0
ichi = i
for ii in range(n):
ichi = p[ichi] - 1
wk += c[ichi]
wk2 = max(wk2, wk)
if i == ichi:
kaisuu[i] = ii + 1
score[i] = wk
score_max[i] = wk2
break
wk = 0
ans = - 10 ** 20
for i in range(n):
ichi = p[i] - 1
wk = c[ichi]
wk2 = c[ichi]
idx = 0
while idx < k - 1:
ichi = p[ichi] - 1
wk += c[ichi]
wk2 = max(wk2, wk)
idx += 1
# ループするならメモを使って減らす
if (k - 1 - idx > kaisuu[ichi] * 2) and kaisuu[ichi] > 0:
roopsuu = ((k - 1 - idx) // kaisuu[ichi]) - 1
wk += roopsuu * score[ichi]
idx += roopsuu * kaisuu[ichi]
wk2 = max(wk2, max(wk, score_max[ichi]))
ans = max(ans, wk2)
print(ans)
if __name__ == '__main__':
main()
| p02585 |
import sys
input = sys.stdin.readline
#from itertools import accumulate
#from itertools import combinations
N,K = list(map(int,input().split()))
P = list(map(int,input().split()))
C = list(map(int,input().split()))
#N,K = 4,4
#P = [2,3,4,1]
#C = [-9,9,1,-1]
visited = [False]*(N+1)
loops = []
for v in range(1,N+1):
if visited[v]:
continue
l = [v]
while True:
v = l[-1]
visited[v] = True
nv = P[v-1]
if visited[nv]:
break
l.append(nv)
loops.append(l)
cand = []
for loop in loops:
temp = 0
vals = [C[i-1] for i in loop]
l = len(vals)
vals2 = vals+vals[:-1]
vals3 = vals+vals+vals[:-1]
cumsum = [0]
for v in vals3:
cumsum.append(cumsum[-1] + v)
#cumsum = [0] + list(accumulate(vals2))
gh = []
#print(vals)
if K <= l:
temp = 0
for left in range(0,2*l-K):
for right in range(left+1,left+K+1):
gh.append(cumsum[right] - cumsum[left])
if gh:
temp = max(gh)
else:
temp = 0
s = sum(vals)
q, r = divmod(K,l)
q -= 1
r += l
for left in range(0,3*l-r):
for right in range(left+1,left+r+1):
#print(left,right)
gh.append(cumsum[right] - cumsum[left])
if gh:
temp = max(gh)
if s > 0:
temp += q * s
cand.append(temp)
print((max(cand)))
| import sys
input = sys.stdin.readline
#from itertools import accumulate
#from itertools import combinations
N,K = list(map(int,input().split()))
P = list(map(int,input().split()))
C = list(map(int,input().split()))
#N,K = 4,4
#P = [2,3,4,1]
#C = [-9,9,1,-1]
#N = 5000
#K = 10**8
#P = [i+1 for i in range(1,5000)] + [1]
#C = [10**9] * N
visited = [False]*(N+1)
loops = []
for v in range(1,N+1):
if visited[v]:
continue
l = [v]
while True:
v = l[-1]
visited[v] = True
nv = P[v-1]
if visited[nv]:
break
l.append(nv)
loops.append(l)
cand = []
for loop in loops:
temp = 0
vals = [C[i-1] for i in loop]
l = len(vals)
vals3 = vals+vals+vals[:-1]
cumsum = [0]
for v in vals3:
cumsum.append(cumsum[-1] + v)
gh = []
#print(vals)
if K <= l:
temp = 0
ma = min(vals)
for left in range(0,2*l-K):
for right in range(left+1,left+K+1):
ma = max(ma,(cumsum[right] - cumsum[left]))
temp += ma
else:
temp = 0
s = sum(vals)
q, r = divmod(K,l)
q -= 1
r += l
ma = min(vals)
for left in range(0,3*l-r):
for right in range(left+1,left+r+1):
ma = max(ma,(cumsum[right] - cumsum[left]))
temp += ma
if s > 0:
temp += q * s
cand.append(temp)
print((max(cand)))
| p02585 |
import sys
sys.setrecursionlimit(10**7)
readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print(('\n'.join(map(str,x))))
def printline(x):print((' '.join(map(str,x))))
from itertools import accumulate
def circle_sum_max(circle,num):
n = len(circle)
s = sum(circle)
if num == 0:
ans = 0
elif num == 1:
ans = max(circle)
else:
ac = list(accumulate([0]+circle))
l = 0
r = 1
ans = ac[r]-ac[l]
i = 0
while r!=n or i%2==1:
if i%2==0:
r = ac[r+1:l+num+1].index(max(ac[r+1:l+num+1])) + r+1
else:
l = ac[l+1:r].index(min(ac[l+1:r])) + l+1
i+=1
ans = max(ans,ac[r]-ac[l])
num = n-num
l = 0
r = num
i = 0
ans = max(ans,s-ac[r]+ac[l])
while r!=n or i%2==1:
if i%2==0:
r = ac[r+1:l+n].index(min(ac[r+1:l+n])) + r+1
else:
l = ac[l+1:r-num+1].index(max(ac[l+1:r-num+1])) + l+1
i+=1
ans = max(ans,s-ac[r]+ac[l])
return ans
n,k = readints()
p = [x-1 for x in readints()]
c = readints()
circles = []
used = [0]*n
for i in range(n):
if not used[i]:
circles.append([c[i]])
used[i] = 1
j = p[i]
while not used[j]:
circles[-1].append(c[j])
used[j] = 1
j = p[j]
score = -10**20
for cir in circles:
m = len(cir)
a = sum(cir)
if k>m:
if a>0:
score = max(score, (k//m)*a + circle_sum_max(cir,k%m), (k//m-1)*a + circle_sum_max(cir,m))
else:
score = max(score,circle_sum_max(cir,m))
else:
score = max(score,circle_sum_max(cir,k))
print(score)
| import sys
sys.setrecursionlimit(10**7)
readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print(('\n'.join(map(str,x))))
def printline(x):print((' '.join(map(str,x))))
from itertools import accumulate
def sum_max(line,n_min,n_max):
n = len(line)
ac = list(accumulate([0]+line))
l = 0
r = n_min
ans = ac[r]-ac[l]
i = 0
if n_min==n_max:
for i in range(n-n_min+1):
ans = max(ans,ac[i+n_min]-ac[i])
else:
while r!=n or i%2==1:
if i%2==0:
r = ac[r+1:l+n_max+1].index(max(ac[r+1:l+n_max+1])) + r+1
else:
l = ac[l+1:r-n_min+1].index(min(ac[l+1:r-n_min+1])) + l+1
i+=1
ans = max(ans,ac[r]-ac[l])
return ans
def sum_min(line,n_min,n_max):
n = len(line)
ac = list(accumulate([0]+line))
l = 0
r = n_min
ans = ac[r]-ac[l]
i = 0
if n_min==n_max:
for i in range(n-n_min+1):
ans = min(ans,ac[i+n_min]-ac[i])
else:
while r!=n or i%2==1:
if i%2==0:
r = ac[r+1:l+n_max+1].index(min(ac[r+1:l+n_max+1])) + r+1
else:
l = ac[l+1:r-n_min+1].index(max(ac[l+1:r-n_min+1])) + l+1
i+=1
ans = min(ans,ac[r]-ac[l])
return ans
def circle_sum_max(circle,num):
n = len(circle)
s = sum(circle)
if num == 0:
ans = 0
else:
ans = max(sum_max(circle,1,num), s-sum_min(circle,n-num,n-1))
return ans
n,k = readints()
p = [x-1 for x in readints()]
c = readints()
circles = []
used = [0]*n
for i in range(n):
if not used[i]:
circles.append([c[i]])
used[i] = 1
j = p[i]
while not used[j]:
circles[-1].append(c[j])
used[j] = 1
j = p[j]
score = -10**20
for cir in circles:
m = len(cir)
a = sum(cir)
if k>m:
if a>0:
score = max(score, (k//m)*a + circle_sum_max(cir,k%m), (k//m-1)*a + circle_sum_max(cir,m))
else:
score = max(score,circle_sum_max(cir,m))
else:
score = max(score,circle_sum_max(cir,k))
print(score)
| p02585 |
from collections import defaultdict
INF = float('inf')
N, K = [int(x) for x in input().split()]
P = [0] + [int(x) for x in input().split()]
C = [0] + [int(x) for x in input().split()]
max_score = -INF
for init in range(1, N + 1): # 初めの場所をiとする
score = defaultdict(int) # int/bool/list....
visited = [-1] * (N + 1)
visited[init] = 0 # 何回移動後に着いたか?
i = init
# max_init = -INF
for k in range(1, K + 1):
prev = i
i = P[i] # k回移動後に着くところ
if visited[i] < 0: # まだ訪れてなかった
visited[i] = k
score[i] = score[prev] + C[i]
# max_init = max(max_init, score[i])
max_score = max(max_score, score[i])
continue
loop_score = (score[prev] + C[i]) - score[i]
loop_len = k - visited[i]
score[i] = score[prev] + C[i]
# max_init = max(max_init, score[i])
max_score = max(max_score, score[i])
if k == K:
break # これ以上移動できない
start = i # ループを開始するノード
loop_num = (K - k) // loop_len # ループをあと何回回れるか
loop_rem = (K - k) % loop_len
if loop_rem == 0:
loop_num -= 1
loop_rem = loop_len
jj = start
temp = 0
temp_max = 0
for l in range(loop_rem):
jj = P[jj]
temp += C[jj]
temp_max = max(temp_max, temp)
loop_max = temp_max + loop_num * loop_score
# max_init = max(max_init, score[start] + loop_max)
max_score = max(max_score, score[start] + loop_max)
break
# max_score = max(max_score, max_init)
if max_score == -INF:
max_score = max(C[1:])
print(max_score) | from collections import defaultdict
N, K = [int(x) for x in input().split()]
P = [0] + [int(x) for x in input().split()]
C = [0] + [int(x) for x in input().split()]
max_score = max(C[1:])
for init in range(1, N + 1): # 初めの場所をiとする
score = defaultdict(int) # int/bool/list....
visited = [-1] * (N + 1)
visited[init] = 0 # 何回移動後に着いたか?
i = init
for k in range(1, K + 1):
prev = i
i = P[i] # k回移動後に着くところ
if visited[i] < 0: # まだ訪れてなかった
visited[i] = k
score[i] = score[prev] + C[i]
max_score = max(max_score, score[i])
continue
loop_score = (score[prev] + C[i]) - score[i]
loop_len = k - visited[i]
score[i] = score[prev] + C[i]
# max_score = max(max_score, score[i])
# if k == K:
# break # これ以上移動できない
start = i # ループを開始するノード
loop_num = (K - k) // loop_len # ループをあと何回回れるか
loop_rem = (K - k) % loop_len
if loop_num > 0 and loop_rem == 0:
loop_num -= 1
loop_rem = loop_len
jj = start
temp = 0
temp_max = 0
for l in range(loop_rem):
jj = P[jj]
temp += C[jj]
temp_max = max(temp_max, temp)
loop_max = temp_max + loop_num * loop_score
max_score = max(max_score, score[start] + loop_max)
break
print(max_score) | p02585 |
from collections import defaultdict
N, K = [int(x) for x in input().split()]
P = [0] + [int(x) for x in input().split()]
C = [0] + [int(x) for x in input().split()]
max_score = max(C[1:])
for init in range(1, N + 1): # 初めの場所をiとする
score = defaultdict(int) # int/bool/list....
visited = [-1] * (N + 1)
visited[init] = 0 # 何回移動後に着いたか?
i = init
for k in range(1, K + 1):
prev = i
i = P[i] # k回移動後に着くところ
if visited[i] < 0: # まだ訪れてなかった
visited[i] = k
score[i] = score[prev] + C[i]
max_score = max(max_score, score[i])
continue
loop_score = (score[prev] + C[i]) - score[i]
loop_len = k - visited[i]
score[i] = score[prev] + C[i]
loop_num = (K - k) // loop_len # ループをあと何回回れるか
loop_rem = (K - k) % loop_len
if loop_num > 0 and loop_rem == 0:
loop_num -= 1
loop_rem = loop_len
j = i # ループを開始するノードから
temp = 0
rem_max = 0
for _ in range(loop_rem):
j = P[j]
temp += C[j]
rem_max = max(rem_max, temp)
max_score = max(max_score, score[i] + loop_num * loop_score + rem_max)
break
print(max_score) | N, K = [int(x) for x in input().split()]
P = [0] + [int(x) for x in input().split()]
C = [0] + [int(x) for x in input().split()]
max_score = max(C[1:])
for init in range(1, N + 1): # 初めの場所をinitとする
score = [0] # k回移動後のスコア
i = init
for k in range(1, K + 1):
i = P[i] # k回移動後に着くところ
score.append(score[-1] + C[i])
max_score = max(max_score, score[k])
if i == init: # ループ検出
loop_score = score[-1]
loop_len = k
if loop_score < 0:
max_score = max(max_score, max(score[1:]))
else:
max_score = max(max_score, max(score[j] + loop_score * ((K - j) // loop_len) for j in range(1, loop_len + 1)))
break
print(max_score) | p02585 |
N, K = [int(x) for x in input().split()]
P = [0] + [int(x) for x in input().split()]
C = [0] + [int(x) for x in input().split()]
max_score = max(C[1:])
for init in range(1, N + 1): # 初めの場所をinitとする
score = [0] # k回移動後のスコア
i = init
for k in range(1, K + 1):
i = P[i] # k回移動後に着くところ
score.append(score[-1] + C[i])
max_score = max(max_score, score[k])
if i == init: # ループ検出
loop_score = score[-1]
loop_len = k
if loop_score < 0:
max_score = max(max_score, max(score[1:]))
else:
max_score = max(max_score, max(score[j] + loop_score * ((K - j) // loop_len) for j in range(1, loop_len + 1)))
break
print(max_score) | N, K = [int(x) for x in input().split()]
P = [0] + [int(x) for x in input().split()]
C = [0] + [int(x) for x in input().split()]
max_score = max(C[1:])
for init in range(1, N + 1): # 初めの場所をinitとする
score = [0] # k回移動後のスコア
i = init
for k in range(1, K + 1):
i = P[i] # k回移動後に着くところ
score.append(score[-1] + C[i])
max_score = max(max_score, score[k])
if i == init: # ループ検出
loop_score = score[-1]
loop_len = k
if loop_score > 0:
max_score = max(max_score, max(score[j] + loop_score * ((K - j) // loop_len) for j in range(1, loop_len + 1)))
break
print(max_score) | p02585 |
n, k = list(map(int,input().split()))
p = list(map(int,input().split()))
c = list(map(int,input().split()))
ans = -float('inf')
for i in range(n):
score = []
check = [0] * n
now = i
cycle = 0
for _ in range(k):
go = p[now] - 1
if check[go] == 1:
break
now = go
if len(score) == 0:
score.append(c[now])
else:
score.append(score[-1] + c[now])
check[now] = 1
cycle += 1
t = k // cycle
m = k % cycle
sum_cycle = score[-1]
if m == 0:
ans = max(sum_cycle * t, max(score), ans)
else:
ans = max(sum_cycle * t + max(score[:m]), max(score), ans)
#print('sum_cycle:', sum_cycle, 'cycle:', cycle, 'ans:', ans)
#print(i+1, score)
print(ans) | n, k = list(map(int,input().split()))
p = list(map(int,input().split()))
c = list(map(int,input().split()))
ans = -float('inf')
for i in range(n):
score = []
check = [0] * n
now = i
cycle = 0
for _ in range(k):
go = p[now] - 1
if check[go] == 1:
break
now = go
if len(score) == 0:
score.append(c[now])
else:
score.append(score[-1] + c[now])
check[now] = 1
cycle += 1
t = k // cycle
m = k % cycle
sum_cycle = score[-1]
if m == 0:
ans = max(sum_cycle * t, sum_cycle * (t - 1) + max(score), max(score), ans)
else:
ans = max(sum_cycle * t + max(score[:m]), sum_cycle * (t - 1) + max(score), max(score), ans)
print(ans) | p02585 |
n, k = list(map(int, input().split()))
# 先頭に0番要素を追加すれば、配列の要素番号と入力pが一致する
p = [0] + list(map(int, input().split()))
c = [0] + list(map(int, input().split()))
ans = -1e9*1e9
s = [None] * n
# 開始ノードをsi
for si in range(1, n+1):
# 閉ループのスコアを取り出す
x = si
#s = list() # ノードの各スコアを保存
s_len = 0
tot = 0 # ループ1周期のスコア
while 1:
x = p[x]
#s.append(c[x])
s[s_len] = c[x]
s_len += 1
tot += c[x]
if (x == si): break # 始点に戻ったら終了
# siを開始とする閉ループのスコア(s)を全探
#s_len = len(s)
t = 0
for i in range(s_len):
t += s[i] # i回移動したときのスコア
if (i+1 > k): break # 移動回数の上限を超えたら終了
# 1周期のスコアが正ならば、可能な限り周回する
if tot > 0:
e = (k-(i+1))//s_len # 周回数
now = t + tot*e # i回移動と周回スコアの合計
else:
now = t
ans = max(ans, now)
print(ans)
| n, k = list(map(int, input().split()))
# 先頭に0番要素を追加すれば、配列の要素番号と入力pが一致する
p = [0] + list(map(int, input().split()))
c = [0] + list(map(int, input().split()))
ans = -float('inf')
# 開始ノードをsi
for si in range(1, n+1):
# 閉ループのスコアを取り出す
x = si
s = list() # ノードの各スコアを保存
#s_len = 0
tot = 0 # ループ1周期のスコア
while 1:
x = p[x]
s.append(c[x])
#s[s_len] = c[x]
#s_len += 1
tot += c[x]
if (x == si): break # 始点に戻ったら終了
# siを開始とする閉ループのスコア(s)を全探
s_len = len(s)
t = 0
for i in range(s_len):
t += s[i] # i回移動したときのスコア
if (i+1 > k): break # 移動回数の上限を超えたら終了
# 1周期のスコアが正ならば、可能な限り周回する
if tot > 0:
e = (k-(i+1))//s_len # 周回数
now = t + tot*e # i回移動と周回スコアの合計
else:
now = t
ans = max(ans, now)
print(ans)
| p02585 |
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1 # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7
def debug(*x):
print(*x, file=sys.stderr)
def solve0(N, K, PS, CS):
PS = [x - 1 for x in PS]
debug(": PS", PS)
CS = [CS[PS[i]] for i in range(N)]
PSS = [PS]
CSS = [CS]
prevPS = PS
prevCS = CS
for i in range(30):
PS2 = [prevPS[prevPS[i]] for i in range(N)]
CS2 = [prevCS[i] + prevCS[prevPS[i]] for i in range(N)]
PSS.append(PS2)
CSS.append(CS2)
prevPS = PS2
prevCS = CS2
score = [0] * N
pos = list(range(N))
length = [0] * N
maxbit = K.bit_length() - 1
for i in range(maxbit, -1, -1):
# debug(": i", i)
# debug(": 2**i", 2**i)
# debug(": CSS[i]", CSS[i])
# debug(": PSS[i]", PSS[i])
# debug(": score", score)
# debug(": length", length)
for j in range(N):
# debug(": length[j] + 2 ** i <= K", length[j] + 2 ** i <= K)
# debug(": CSS[i][pos[j]]", CSS[i][pos[j]])
if length[j] + 2 ** i <= K and CSS[i][pos[j]] > 0:
# debug("add: j", j)
score[j] += CSS[i][pos[j]]
pos[j] = PSS[i][pos[j]]
length[j] += 2 ** i
# if CSS[i][j] > score[j]:
# # debug("reset: j", j)
# # debug(": CSS[i][i], score[j]", CSS[i][i], score[j])
# pos[j] = PSS[i][j]
# score[j] = CSS[i][j]
# length[j] = 2 ** i
# debug("finish: score", score)
ret = max(score)
if ret == 0:
ret = max(CS)
return ret
def solve(N, K, PS, CS):
PS = [x - 1 for x in PS]
CS = [CS[PS[i]] for i in range(N)]
visited = {}
loops = []
loopScore = []
for i in range(N):
loop = []
c = 0
while i not in visited:
visited[i] = True
c += CS[i]
i = PS[i]
loop.append(i)
if loop:
loops.append(loop)
loopScore.append(c)
# debug(": loops", loops)
# debug(": loopScore", loopScore)
scores = [0] * N
pos = list(range(N))
from collections import defaultdict
ret = 0
for i, loop in enumerate(loops):
if loopScore[i] > 0:
baseScore = loopScore[i] * (K // len(loop))
r = K % len(loop)
if r == 0:
r = len(loop)
baseScore -= loopScore[i]
# debug("r==0: baseScore", baseScore)
maxscore = 0
scores = defaultdict(int)
for i in range(r):
for x in loop:
scores[x] += CS[pos[x]]
pos[x] = PS[pos[x]]
maxscore = max(maxscore, max(scores.values()))
# debug("posi: maxscores", scores)
ret = max(maxscore + baseScore, ret)
else:
r = len(loop)
maxscore = -INF
scores = defaultdict(int)
for i in range(r):
for x in loop:
scores[x] += CS[pos[x]]
pos[x] = PS[pos[x]]
# debug("neg: scores", scores)
maxscore = max(maxscore, max(scores.values()))
ret = max(maxscore, ret)
if ret == 0:
ret = max(CS)
return ret
def main():
# parse input
N, K = map(int, input().split())
PS = list(map(int, input().split()))
CS = list(map(int, input().split()))
print(solve(N, K, PS, CS))
# tests
T1 = """
5 2
2 4 5 1 3
3 4 -10 -8 8
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
8
"""
T2 = """
2 3
2 1
10 -7
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
13
"""
T3 = """
3 3
3 1 2
-1000 -2000 -3000
"""
TEST_T3 = """
>>> as_input(T3)
>>> main()
-1000
"""
T4 = """
10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719
"""
TEST_T4 = """
>>> as_input(T4)
>>> main()
29507023469
"""
T5 = """
3 1000
2 3 1
1 0 2
"""
TEST_T5 = """
>>> as_input(T5)
>>> main()
1001
"""
T6 = """
3 1000
2 3 1
1 1 -3
"""
TEST_T6 = """
>>> as_input(T6)
>>> main()
2
"""
T7 = """
4 1000
2 1 4 3
1 1 -10000 10000
"""
TEST_T7 = """
>>> as_input(T7)
>>> main()
10000
"""
T8 = """
4 1000
2 1 4 3
1 1 -10000 10001
"""
TEST_T8 = """
>>> as_input(T8)
>>> main()
10001
"""
def _test():
import doctest
doctest.testmod()
g = globals()
for k in sorted(g):
if k.startswith("TEST_"):
doctest.run_docstring_examples(g[k], g, name=k)
def as_input(s):
"use in test, use given string as input file"
import io
f = io.StringIO(s.strip())
g = globals()
g["input"] = lambda: bytes(f.readline(), "ascii")
g["read"] = lambda: bytes(f.read(), "ascii")
input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
if sys.argv[-1] == "-t":
print("testing")
_test()
sys.exit()
main()
| #!/usr/bin/env python3
import sys
from collections import defaultdict
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1 # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7
def debug(*x):
print(*x, file=sys.stderr)
def solve(N, K, PS, CS):
PS = [x - 1 for x in PS]
CS = [CS[PS[i]] for i in range(N)]
visited = {}
loops = []
loopScore = []
for i in range(N):
loop = []
c = 0
while i not in visited:
visited[i] = True
c += CS[i]
i = PS[i]
loop.append(i)
if loop:
loops.append(loop)
loopScore.append(c)
pos = list(range(N))
ret = -INF
for i, loop in enumerate(loops):
if loopScore[i] > 0:
baseScore = loopScore[i] * (K // len(loop))
r = K % len(loop)
if r == 0:
r = len(loop)
baseScore -= loopScore[i]
maxscore = 0
scores = defaultdict(int)
for i in range(r):
for x in loop:
scores[x] += CS[pos[x]]
pos[x] = PS[pos[x]]
maxscore = max(maxscore, max(scores.values()))
ret = max(maxscore + baseScore, ret)
else:
r = len(loop)
maxscore = -INF
scores = defaultdict(int)
for i in range(r):
for x in loop:
scores[x] += CS[pos[x]]
pos[x] = PS[pos[x]]
maxscore = max(maxscore, max(scores.values()))
ret = max(maxscore, ret)
return ret
def main():
# parse input
N, K = map(int, input().split())
PS = list(map(int, input().split()))
CS = list(map(int, input().split()))
print(solve(N, K, PS, CS))
# tests
T1 = """
5 2
2 4 5 1 3
3 4 -10 -8 8
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
8
"""
T2 = """
2 3
2 1
10 -7
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
13
"""
T3 = """
3 3
3 1 2
-1000 -2000 -3000
"""
TEST_T3 = """
>>> as_input(T3)
>>> main()
-1000
"""
T4 = """
10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719
"""
TEST_T4 = """
>>> as_input(T4)
>>> main()
29507023469
"""
T5 = """
3 1000
2 3 1
1 0 2
"""
TEST_T5 = """
>>> as_input(T5)
>>> main()
1001
"""
T6 = """
3 1000
2 3 1
1 1 -3
"""
TEST_T6 = """
>>> as_input(T6)
>>> main()
2
"""
T7 = """
4 1000
2 1 4 3
1 1 -10000 10000
"""
TEST_T7 = """
>>> as_input(T7)
>>> main()
10000
"""
T8 = """
4 1000
2 1 4 3
1 1 -10000 10001
"""
TEST_T8 = """
>>> as_input(T8)
>>> main()
10500
"""
def _test():
import doctest
doctest.testmod()
g = globals()
for k in sorted(g):
if k.startswith("TEST_"):
doctest.run_docstring_examples(g[k], g, name=k)
def as_input(s):
"use in test, use given string as input file"
import io
f = io.StringIO(s.strip())
g = globals()
g["input"] = lambda: bytes(f.readline(), "ascii")
g["read"] = lambda: bytes(f.read(), "ascii")
input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
if sys.argv[-1] == "-t":
print("testing")
_test()
sys.exit()
main()
| p02585 |
n, k = list(map(int, input().split()))
p = list(map(int, input().split()))
p = [x-1 for x in p]
c = list(map(int, input().split()))
visited = [False for _ in range(n)]
lp = []
lp_cum = []
lp_sum = []
range_s = []
for i in range(n):
if not visited[i]:
lp.append([i])
lp_cum.append([0, c[i]])
visited[i] = True
while not visited[p[lp[-1][-1]]]:
lp[-1].append(p[lp[-1][-1]])
lp_cum[-1].append(lp_cum[-1][-1] + c[lp[-1][-1]])
visited[lp[-1][-1]] = True
lp_sum.append((lp_cum[-1][-1], len(lp[-1])))
range_s.append(set())
for x in range(1, len(lp_cum[-1])):
for y in range(x):
range_s[-1].add((lp_cum[-1][x] - lp_cum[-1][y], x-y))
if x < len(lp_cum[-1])-1 or y > 0:
range_s[-1].add((lp_cum[-1][-1] - lp_cum[-1][x] + lp_cum[-1][y], len(lp[-1])-x+y))
ok, ng = -10**9, 10**18+1
while ng-ok > 1:
x = (ok+ng)//2
flg = False
for i in range(len(lp)):
s_sum, s_num = lp_sum[i]
if s_sum <= 0:
for r_sum, r_num in range_s[i]:
if r_sum >= x and r_num <= k:
flg = True
break
else:
for r_sum, r_num in range_s[i]:
if r_num > k:
continue
if r_sum >= x:
flg = True
break
rep = (x-1-r_sum) // s_sum + 1
if rep * s_num + r_num <= k:
flg = True
break
if flg:
ok = x
else:
ng = x
print(ok) | n, k = list(map(int, input().split()))
p = list(map(int, input().split()))
p = [x-1 for x in p]
c = list(map(int, input().split()))
visited = [False for _ in range(n)]
lp = []
lp_cum = []
ans = -10**9
for i in range(n):
if not visited[i]:
lp.append([i])
lp_cum.append([0, c[i]])
visited[i] = True
while not visited[p[lp[-1][-1]]]:
lp[-1].append(p[lp[-1][-1]])
lp_cum[-1].append(lp_cum[-1][-1] + c[lp[-1][-1]])
visited[lp[-1][-1]] = True
t_sum, t_num = lp_cum[-1][-1], len(lp[-1])
for x in range(1, len(lp_cum[-1])):
for y in range(x):
r_sum, r_num = lp_cum[-1][x] - lp_cum[-1][y], x-y
if t_sum <= 0:
if r_num <= k:
ans = max(ans, r_sum)
else:
if r_num <= k:
ans = max(ans, r_sum + t_sum * ((k - r_num) // t_num))
if x < len(lp_cum[-1])-1 or y > 0:
r_sum, r_num = lp_cum[-1][-1] - lp_cum[-1][x] + lp_cum[-1][y], len(lp[-1])-x+y
if t_sum <= 0:
if r_num <= k:
ans = max(ans, r_sum)
else:
if r_num <= k:
ans = max(ans, r_sum + t_sum * ((k - r_num) // t_num))
print(ans) | p02585 |
N,K=list(map(int,input().split()))
P=list([int(x)-1 for x in input().split()])
C=list(map(int,input().split()))
dp = []
init = 0
if K<=N:
ans = set()
for i in range(N):
tmp,now,last = [0],i,0
for _ in range(K):
last += C[P[now]]
ans.add(last)
now=P[now]
print((max(ans)))
exit()
ans = -10**9
for i in range(N):
tmp,now,done = [0],i,set()
for _ in range(N+1):
#while now not in done:
tmp.append(tmp[-1]+C[P[now]])
if P[now] == i:
break
now = P[now]
tmp = tmp[1:]
cnt = len(tmp)
m = max(tmp)
ans = max(ans,m,tmp[-1]*(K//cnt-1)+m)
if K%cnt != 0:
ans = max(ans, tmp[-1]*(K//cnt)+max(tmp[:K%cnt]))
#print(i,ans,tmp)
print(ans)
| N,K=list(map(int,input().split()))
P=list([int(x)-1 for x in input().split()])
C=list(map(int,input().split()))
if K<=N:
ans = -10**9
for i in range(N):
now,last = i,0
for _ in range(K):
last += C[P[now]]
ans = max(ans,last)
now=P[now]
print(ans)
exit()
ans = -10**9
for i in range(N):
tmp,now,done = [0],i,set()
for _ in range(N+1):
#while now not in done:
tmp.append(tmp[-1]+C[P[now]])
if P[now] == i:
break
now = P[now]
tmp = tmp[1:]
cnt = len(tmp)
m = max(tmp)
ans = max(ans,m,tmp[-1]*(K//cnt-1)+m)
if K%cnt != 0:
ans = max(ans, tmp[-1]*(K//cnt)+max(tmp[:K%cnt]))
#print(i,ans,tmp)
print(ans)
| p02585 |
n, k = list(map(int, input().split()))
p = list(map(int, input().split()))
c = list(map(int, input().split()))
for i in range(n):
p[i] -= 1
def score(a, k):
now = p[a]
s = c[now]
cnt = 1
l = [s]
while now != a and cnt < k:
now = p[now]
s += c[now]
l.append(s)
cnt += 1
if cnt == k:
return max(l)
if 2 * cnt >= k:
s = (k // cnt - 1) * s
k %= cnt
k += cnt
else:
k -= cnt
cnt = 0
while cnt < k:
now = p[now]
s += c[now]
l.append(s)
cnt += 1
return max(l)
print((max(score(i, k) for i in range(n)))) | n, k = list(map(int, input().split()))
p = list(map(int, input().split()))
c = list(map(int, input().split()))
for i in range(n):
p[i] -= 1
def score(a, k):
now = p[a]
s = c[now]
cnt = 1
l = [s]
while now != a and cnt < k:
now = p[now]
s += c[now]
l.append(s)
cnt += 1
if cnt == k:
return max(l)
l.append((k // cnt - 1) * s + max(l))
s = (k // cnt) * s
k %= cnt
cnt=0
while cnt < k:
now = p[now]
s += c[now]
l.append(s)
cnt += 1
return max(l)
print((max(score(i, k) for i in range(n))))
| p02585 |
n,k=list(map(int,input().split()))
p=list([int(x)-1 for x in input().split()])
c=list(map(int,input().split()))
ans=-10**20
for i in range(n):
x=[]
for _ in range(k):
i=p[i]
x.append(c[i])
anss=-10**20
s=x[0]
anss=max(anss,s)
for i in x[1:]:
s+=i
anss=max(anss,s)
ans=max(ans,anss)
print(ans) | def solve(n,x,k):
ans=-10**20
s=0
sx=sum(x)
for i in range(n):
if (i+1)>k:break
s+=x[i]
d=((k-i-1)//n)*sx
ans=max(ans,s+d,s)
return ans
n,k=list(map(int,input().split()))
p=list([int(x)-1 for x in input().split()])
c=list(map(int,input().split()))
ans=-10**20
for i in range(n):
x=[c[i]]
j=p[i]
while i!=j:
x.append(c[j])
j=p[j]
x=x[1:]+[x[0]]
ans=max(ans,solve(len(x),x,k))
print(ans) | p02585 |
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(eval(input()))
def MAP(): return list(map(int, input().split()))
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return list(zip(*(MAP() for _ in range(n))))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10
N, K = MAP()
P = LIST()
C = LIST()
check = [0]*N
score = []
i = 0
while 1:
while i < N and check[i]:
i += 1
if i == N:
break
tmp = []
while check[i] == 0:
check[i] = 1
i = P[i]-1
tmp.append(C[i])
score.append(tmp)
ans = -INF
for x in score:
x_acc = list(accumulate([0] + x*3))
n = len(x)
if x_acc[n] <= 0:
tmp_ans = 0
l = min(K, n)
else:
tmp_ans = x_acc[n]*(max(0, K//n-1))
l = min(K%n+n, K)
tmp_max = -INF
for i, j in combinations(list(range(3*n+1)), 2):
if j-i <= l:
if tmp_max < x_acc[j]-x_acc[i]:
tmp_max = x_acc[j]-x_acc[i]
tmp_ans += tmp_max
ans = max(ans, tmp_ans)
print(ans)
| import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(eval(input()))
def MAP(): return list(map(int, input().split()))
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return list(zip(*(MAP() for _ in range(n))))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10
N, K = MAP()
P = LIST()
C = LIST()
check = [0]*N
score = []
i = 0
while 1:
while i < N and check[i]:
i += 1
if i == N:
break
tmp = []
while check[i] == 0:
check[i] = 1
i = P[i]-1
tmp.append(C[i])
score.append(tmp)
ans = -INF
for x in score:
x_acc = list(accumulate([0] + x + x))
n = len(x)
tmp_max = -INF
for i, j in combinations(list(range(2*n+1)), 2):
if j-i <= min(K, n):
if tmp_max < x_acc[j]-x_acc[i]:
tmp_max = x_acc[j]-x_acc[i]
cnt = j-i
tmp_ans = -INF
if 0 >= x_acc[n]:
tmp_ans = tmp_max
else:
if cnt <= K%n:
tmp_ans = x_acc[n]*(K//n) + tmp_max
else:
tmp_max2 = 0
for i, j in combinations(list(range(2*n+1)), 2):
if j-i <= K%n:
if tmp_max2 < x_acc[j]-x_acc[i]:
tmp_max2 = x_acc[j]-x_acc[i]
tmp_ans = max(x_acc[n]*(K//n-1)+tmp_max, x_acc[n]*(K//n) + tmp_max2)
ans = max(ans, tmp_ans)
print(ans)
| p02585 |
n , k = list(map(int,input().split()))
p = list(map(int,input().split()))
c = list(map(int,input().split()))
loop = []
visit = [False for i in range(n)]
for i in range(n):
if visit[i]:
continue
tyu = [i]
now = i
visit[i] = True
while True:
nex = p[now] - 1
if nex == i:
break
visit[nex] = True
tyu.append(nex)
now = nex
loop.append(tyu)
ans = []
for p in loop:
kouho = []
losum = 0
lokz = len(p)
kar = []
for i in p:
losum += c[i]
kar.append(c[i])
if losum > 0:
kouho.append(losum*(k//lokz))
for i in range(lokz):
for j in range(lokz):
if i < j:
amari = j - i
if amari <= k:
cou = losum*((k-amari)//lokz) + sum(kar[i:j])
elif i == j:
continue
elif i > j:
amari = lokz - (i-j)
if amari <= k:
cou = losum*((k-amari)//lokz) + sum(kar[:j]) + sum(kar[i:])
kouho.append(cou)
elif losum <= 0:
for i in range(lokz):
for j in range(lokz):
if i <= j:
amari = j - i
if amari <= k:
cou = sum(kar[i:j+1])
elif i > j:
amari = lokz - (i-j)
if amari <= k:
cou = sum(kar[:j+1]) + sum(kar[i:])
kouho.append(cou)
ans.append(max(kouho))
print((max(ans)))
| n , k = list(map(int,input().split()))
p = list(map(int,input().split()))
c = list(map(int,input().split()))
loop = []
visit = [(-1,-1) for i in range(n)]
cou = -1
for i in range(n):
if visit[i] != (-1,-1):
continue
cou += 1
tyu = [i]
now = i
visit[i] = (cou,0)
t = 1
while True:
nex = p[now] - 1
if nex == i:
break
visit[nex] = (cou,t)
tyu.append(nex)
now = nex
t += 1
loop.append(tyu)
ans = []
for i in range(n):
p = loop[visit[i][0]][visit[i][1]:] + loop[visit[i][0]][:visit[i][1]]
kar = [0]
kouho = []
losum = 0
lokz = len(p)
for j in p:
losum += c[j]
kar.append(kar[-1] + c[j])
if losum >= 0:
for l in range(lokz+1):
if l > k:
break
cou = losum*((k-l)//lokz) + kar[l]
kouho.append(cou)
elif losum < 0:
for l in range(1,lokz+1):
if l > k:
break
cou = kar[l]
kouho.append(cou)
ans.append(max(kouho))
print((max(ans)))
| p02585 |
# from pathlib import Path
"""
解説動画のコードを参考にしました
https://atcoder.jp/contests/abc175/submissions/15945829
"""
stdin = iter(
list(map(int, l.split())) for l in
# Path('./test/sample-4.in').read_text().split('\n')
open(0).read().split('\n')
)
N,K = next(stdin)
*P, = next(stdin)
*C, = next(stdin)
ans = int(-1e18)
for start in P:
pos = start
scores = [] # スコア格納用
while True:
pos = P[pos-1] # 移動
scores.append(C[pos-1]) # スコアの格納
# 1周したかどうか
if pos == start: break
# 周期途中のどこでやめるか判定
L = len(scores)
S = sum(scores)
period_score = 0
for i in range(L):
period_score += scores[i] # スコアの加算
# 試行回数を超えていないか
if i+1 > K: break
total_score = period_score
# 1周期の合計スコアが正なら、周期を重ねるごとにスコア増
if S > 0:
total_score += S * ((K-(i+1)) // L)
ans = max(ans, total_score)
print(ans) | """
解説動画のコードを参考にしました
https://atcoder.jp/contests/abc175/submissions/15945829
"""
N,K = list(map(int, input().split()))
*P, = list(map(int, input().split()))
*C, = list(map(int, input().split()))
ans = int(-1e18)
for start in P:
pos = start
scores = [] # スコア格納用
while True:
pos = P[pos-1] # 移動
scores.append(C[pos-1]) # スコアの格納
# 1周したかどうか
if pos == start: break
# 周期途中のどこでやめるか判定
L = len(scores)
S = sum(scores)
period_score = 0
for i in range(L):
period_score += scores[i] # スコアの加算
# 試行回数を超えていないか
if i+1 > K: break
total_score = period_score
# 1周期の合計スコアが正なら、周期を重ねるごとにスコア増
if S > 0:
total_score += S * ((K-(i+1)) // L)
ans = max(ans, total_score)
print(ans)
| p02585 |
from itertools import accumulate
def solve(n, k, ppp, ccc):
NINF = -(10 ** 18)
ans = NINF
checked = [False] * n
for s in range(n):
if checked[s] == True:
continue
checked[s] = True
scores = [ccc[ppp[s]]]
starts = [s]
v = ppp[s]
while v != s:
scores.append(ccc[ppp[v]])
starts.append(v)
checked[v] = True
v = ppp[v]
l = len(scores)
d, m = divmod(k, l)
loop = sum(scores)
if d > 0:
d -= 1
m += l
base = max(0, loop * d)
for s in starts:
v = ppp[s]
score = base + ccc[ppp[s]]
best_score = score
for _ in range(m - 1):
score += ccc[ppp[v]]
v = ppp[v]
best_score = max(best_score, score)
ans = max(ans, best_score)
return ans
n, k = list(map(int, input().split()))
ppp = list(map(int, input().split()))
ppp = [p - 1 for p in ppp]
ccc = list(map(int, input().split()))
print((solve(n, k, ppp, ccc)))
| from itertools import accumulate
def solve(n, k, ppp, ccc):
NINF = -(10 ** 18)
ans = NINF
checked = [False] * n
for s in range(n):
if checked[s] == True:
continue
checked[s] = True
scores = [ccc[ppp[s]]]
v = ppp[s]
while v != s:
scores.append(ccc[ppp[v]])
checked[v] = True
v = ppp[v]
l = len(scores)
d, m = divmod(k, l)
loop = sum(scores)
if d > 0:
d -= 1
m += l
scores += scores * 2
scores.insert(0, 0)
acc = list(accumulate(scores))
tmp = max(max(acc[i + 1:i + m + 1]) - acc[i] for i in range(l))
ans = max(ans, tmp, loop * d + tmp)
return ans
n, k = list(map(int, input().split()))
ppp = list(map(int, input().split()))
ppp = [p - 1 for p in ppp]
ccc = list(map(int, input().split()))
print((solve(n, k, ppp, ccc)))
| p02585 |
n,k=list(map(int,input().split()))
P=list(map(int,input().split()))
C=list(map(int,input().split()))
m=min(C)
score_max=m
for L in range(n):
score=0
d=[0]*n
r=0
d[L]=1
for i in range(k):
r+=1
L=P[L]-1
score+=C[L]
score_max=max(score,score_max)
if d[L]==0:
d[L]=1
elif score<0:
break
else:
roop=k//r
score = score*roop
score_max=max(score,score_max)
h=k%r
for j in range(h):
L=P[L]-1
score+=C[L]
score_max=max(score,score_max)
break
print(score_max)
| n,k=list(map(int,input().split()))
P=list(map(int,input().split()))
C=list(map(int,input().split()))
score_max=max(C)
#スタート地点=L
for L in range(n):
score=0
d=[0]*n
r=0
d[L]=1
#k回移動する
for _ in range(k):
r+=1#移動回数をカウント
L=P[L]-1#移動先の位置
score+=C[L]
score_max=max(score,score_max)
#もしも移動した場所に未到達なら...
if d[L]==0:
d[L]=1
#Cの最小値未満ならスコアは減り続けるのでbreak
elif score<0:
break
else:
roop=(k//r)-1
#最後の1周と端数は一個ずつ見る
h=(k%r)+r
score*=roop
score_max=max(score,score_max)
#あまりの移動回数の処理
for _ in range(h):
L=P[L]-1
score+=C[L]
score_max=max(score,score_max)
break
print(score_max)
| p02585 |
n,k=list(map(int,input().split()))
P=list(map(int,input().split()))
C=list(map(int,input().split()))
score_max=max(C)
#スタート地点=L
for L in range(n):
score=0
d=[0]*n
r=0
d[L]=1
#k回移動する
for _ in range(k):
r+=1#移動回数をカウント
L=P[L]-1#移動先の位置
score+=C[L]
score_max=max(score,score_max)
#もしも移動した場所に未到達なら...
if d[L]==0:
d[L]=1
#Cの最小値未満ならスコアは減り続けるのでbreak
elif score<0:
break
else:
roop=(k//r)-1
#最後の1周と端数は一個ずつ見る
h=(k%r)+r
score*=roop
score_max=max(score,score_max)
#あまりの移動回数の処理
for _ in range(h):
L=P[L]-1
score+=C[L]
score_max=max(score,score_max)
break
print(score_max)
| n,k=list(map(int,input().split()))
P=list(map(int,input().split()))
C=list(map(int,input().split()))
score_max=max(C)
#スタート地点=L
for L in range(n):
score=0
d=[0]*n
r=0
d[L]=1
#k回移動する
for _ in range(k):
r+=1#移動回数をカウント
L=P[L]-1#移動先の位置
score+=C[L]
score_max=max(score,score_max)
#もしも移動した場所に未到達なら...
if d[L]==0:
d[L]=1
#Cの0未満ならスコアは減り続けるのでbreak
elif score<0:
break
else:
#ループ可能回数を調べてscoreにかける
#最後の1周とあまりは一個ずつ見る
roop=(k//r)-1
h=(k%r)+r
score*=roop
score_max=max(score,score_max)
#あまりの移動の処理
for _ in range(h):
L=P[L]-1
score+=C[L]
score_max=max(score,score_max)
break
print(score_max) | p02585 |
def li():
return [int(x) for x in input().split()]
N, K = li()
P = [0] + li()
C = [0] + li()
max_scores = [-10**12] * (N+10)
for init_i in range(1, N+1):
i = init_i
scores = [0]
for l in range(1, K+1):
i = P[i]
score = scores[l-1] + C[i]
scores.append(score)
scores[0] = -10**9
max_scores[i] = max(scores)
print((max(max_scores))) | def li():
return [int(x) for x in input().split()]
N, K = li()
P = [0] + li()
C = [0] + li()
def get_cycle(start_i):
cycle = []
i = start_i
while True:
i = P[i]
if i == start_i:
break
cycle.append(i)
cycle.append(start_i)
return cycle
def get_cycle_scores(cycle):
score = 0
scores = [score]
for i in cycle:
score += C[i]
scores.append(score)
return scores
max_scores = []
for start_i in range(1,N+1):
cycle = get_cycle(start_i)
scores = get_cycle_scores(cycle)
cycle_len = len(cycle)
score_per_cycle = scores[cycle_len]
# 1cycle以下の場合は全て調べればよし
if K <= len(cycle):
max_score = max(scores[move] for move in range(1, K+1))
max_scores.append(max_score)
continue
# 1サイクルごとのスコアがマイナスならサイクルを回らないのがハイスコア
if score_per_cycle <= 0:
max_score = max(scores[move] for move in range(1, cycle_len+1))
max_scores.append(max_score)
continue
# 1サイクルごとのスコアがプラスなら限界までサイクルを回るのがハイスコア
# ラスト1cycleのスコアを調べる
scores_last_cycle = []
for move in range(K-cycle_len+1, K+1):
# 何周したか
loop_cnt = move // cycle_len
# あまり
rest_move = move % cycle_len
# スコア = 1周ごとのスコア * 何周したか + あまり
score = loop_cnt * score_per_cycle + scores[rest_move]
scores_last_cycle.append(score)
max_scores.append(max(scores_last_cycle))
print((max(max_scores)))
| p02585 |
N, K = list(map(int, input().split()))
P, C = [list(map(int, input().split())) for _ in range(2)]
c = [1] * N
m = [[0] * (N+1) for i in range(N)]
for i in range(N):
m[i][1] = (C[P[i]-1])
ans = max(C)
for i in range(N):
j = i
while P[j]-1 != i:
j = P[j]-1
c[i] += 1
m[i][c[i]] = m[i][c[i]-1] + C[P[j]-1]
if m[i][c[i]] > 0:
ans = max(ans, m[i][c[i]] * (K//c[i]-1) + max(m[i] + [m[i][c[i]] + m[i][j+1] for j in range(K%c[i])]))
else:
ans = max(ans, max(m[i][1:min(c[i],K)+1]))
print(ans)
| N, K = list(map(int, input().split()))
P, C = [list(map(int, input().split())) for _ in range(2)]
ans = max(C)
for i in range(N):
m = [0] * (N+1)
k = i
for j in range(N):
m[j+1] = m[j] + C[k]
k = P[k]-1
if k == i:
break
if m[j+1] > 0:
ans = max(ans, m[j+1] * (K//(j+1)-1) + max(m + [m[j+1] + m[k+1] for k in range(K%(j+1))]))
else:
ans = max(ans, max(m[1:min(j+1,K)+1]))
print(ans)
| p02585 |
# O(EV)
def bellman_ford(s):
d = [0]*n # 各頂点への最小コスト
d[s] = 0 # 自身への距離は0
x=s
for tt in range(k):
update = False # 更新が行われたか
aa,bb,cc=g[x][0],g[x][1],g[x][2]
if d[bb] < d[aa] + cc:
d[bb] = d[aa] + cc
update = True
if not update:
break
x=bb
return d
n,k=list(map(int,input().split()))
g=[]
p=list(map(int,input().split()))
c=list(map(int,input().split()))
if max(c)<0:
print((max(c)))
exit()
for i in range(n):
g.append((i,p[i]-1,c[p[i]-1]))
ans=0
for i in range(n):
ans=max(ans,max(bellman_ford(i)))
print(ans) | n,k=list(map(int,input().split()))
p=list(map(int,input().split()))
c=list(map(int,input().split()))
ans=float('inf')*-1
for i in range(n):
visited=[i]
pin=0
now=i
for j in range(k):
now=p[now]-1
pin+=c[now]
ans=max(ans,pin)
visited+=[now]
if visited[0]==visited[-1]:
if pin>0:
pin*=(k//(len(visited)-1)-1)
ans=max(ans,pin)
for s in range(k%(len(visited)-1)+len(visited)-1):
now=p[now]-1
pin+=c[now]
ans=max(ans,pin)
break
else:
break
print(ans) | p02585 |
n,k = list(map(int, input().split()))
p = list(map(int, input().split()))
c = list(map(int, input().split()))
def sim(start,mx): # simulate mx step from start, returns max_score
if mx==0:
return 0
now_p=0
nxt=p[start]-1
cnt=0
p_lis=[]
while True:
nxt=p[nxt]-1
now_p+=c[nxt]
p_lis.append(now_p)
cnt+=1
if cnt==mx:
break
return max(p_lis)
visited_p=set() # already checked flag
cycle_score=[] # cycle loop score
cycle_points=[]
now_cycle=0
for i in range(n):
if i in visited_p:
continue
visited_p.add(i)
now_p=0
nxt=p[i]-1
visited=set()
while True:
nxt=p[nxt]-1
visited_p.add(nxt)
if nxt in visited:
break
visited.add(nxt)
now_p+=c[nxt]
cycle_score.append(now_p)
cycle_points.append(list(visited))
ans=-float('inf')
for c_num in range(len(cycle_score)):
# print(c_num,cycle_score[c_num],cycle_points[c_num])
cycle_len=len(cycle_points[c_num])
for start in cycle_points[c_num]:
if cycle_score[c_num]<0: # no loop, just check min(loop_len,k)
score = sim(start,min(cycle_len,k))
ans=max(ans,score)
else: # loop as many as possible
loop_num = k % cycle_len
nokori=k-(loop_num*cycle_len)
score = sim(start,nokori) + loop_num*cycle_score[c_num]
ans=max(ans,score)
print(ans) | n,k = list(map(int, input().split()))
p = list(map(int, input().split()))
c = list(map(int, input().split()))
def sim(start,mx): # simulate mx step from start, returns max_score
if mx==0:
return 0
now_p=0
nxt=p[start]-1
cnt=0
p_lis=[]
while True:
nxt=p[nxt]-1
now_p+=c[nxt]
p_lis.append(now_p)
cnt+=1
if cnt==mx:
break
return max(p_lis)
visited_p=set() # already checked flag
cycle_score=[] # cycle loop score
cycle_points=[]
now_cycle=0
for i in range(n):
if i in visited_p:
continue
visited_p.add(i)
now_p=0
nxt=p[i]-1
visited=set()
while True:
nxt=p[nxt]-1
visited_p.add(nxt)
if nxt in visited:
break
visited.add(nxt)
now_p+=c[nxt]
cycle_score.append(now_p)
cycle_points.append(list(visited))
ans=-float('inf')
for c_num in range(len(cycle_score)):
# print(c_num,cycle_score[c_num],cycle_points[c_num])
cycle_len=len(cycle_points[c_num])
for start in cycle_points[c_num]:
if cycle_score[c_num]<0: # no loop, just check min(loop_len,k)
score = sim(start,min(cycle_len,k))
ans=max(ans,score)
else: # loop as many as possible
loop_num = max(0,(k // cycle_len) - 1)
nokori=k-loop_num*cycle_len
score = sim(start,nokori) + loop_num*cycle_score[c_num]
ans=max(ans,score)
print(ans)
| p02585 |
def cycle_getter(N, start):
"""
:param N: 移動回数
:param start: 初期条件
:return front: cycleまでの要素のリスト
cycle: cycle内の要素のリスト
end: cycle後の余った部分の要素のリスト
cnt: cycle回数
"""
p = start
front, cycle, end = [], [], []
cnt = 0
visit = {p:0}
L, R = N, -1
for i in range(1,N):
p = lift(p)
if p in visit:
"""
(L, R) = (サイクルに入るまでに移動した回数, サイクルの終端に着くまでに移動した回数)
[6,2,3,4,0,1,2] ⇒ (L, R) = (1, 6)
"""
L, R = visit[p], i
period = R-L
break
visit[p] = i
p = start
for _ in range(L):
front.append(p)
p = lift(p)
if L != N:
for _ in range(L,R):
cycle.append(p)
p = lift(p)
for _ in range(N-(N-L)%period,N):
end.append(p)
p = lift(p)
cnt = (N-L)//period
return front, cycle, end, cnt
################################################################################
import sys
input = sys.stdin.readline
from itertools import accumulate
def lift(x): return P[x-1]
N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
C = list(map(int, input().split()))
res = -float("inf")
for i in range(1,N+1):
front, cycle, end, cnt = cycle_getter(K,i)
S = sum(C[j-1] for j in front)
T = sum(C[j-1] for j in cycle)
if cycle+end:
U = max(0, max(accumulate(C[j-1] for j in cycle+end)))
else: U=0
if front:
R = max(accumulate(C[j-1] for j in front))
else: R=0
res = max(res, S+T*(cnt-1)+U, S+U, R)
print(res) | def cycle_getter(N, start):
"""
:param N: 移動回数
:param start: 初期条件
:return front: cycleまでの要素のリスト
cycle: cycle内の要素のリスト
end: cycle後の余った部分の要素のリスト
cnt: cycle回数
"""
p = start
front, cycle, end = [], [], []
cnt = 0
visit = {p:0}
L, R = N, -1
P = [p]
for i in range(1,N):
p = lift(p)
if p in visit:
"""
(L, R) = (サイクルに入るまでに移動した回数, サイクルの終端に着くまでに移動した回数)
[6,2,3,4,0,1,2] ⇒ (L, R) = (1, 6)
"""
L, R = visit[p], i
period = R-L
break
visit[p] = i
P.append(p)
front = P[:L]
if L != N:
cycle, end = P[L:R], P[L:L+(N-L)%period]
cnt = (N-L)//period
return front, cycle, end, cnt
################################################################################
import sys
input = sys.stdin.readline
from itertools import accumulate
def lift(x): return P[x-1]
N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
C = list(map(int, input().split()))
res = -float("inf")
for i in range(1,N+1):
front, cycle, end, cnt = cycle_getter(K,i)
S = sum(C[j-1] for j in front)
T = sum(C[j-1] for j in cycle)
if cycle+end:
U = max(0, max(accumulate(C[j-1] for j in cycle+end)))
else: U=0
if front:
R = max(accumulate(C[j-1] for j in front))
else: R=0
res = max(res, S+T*(cnt-1)+U, S+U, R)
print(res) | p02585 |
N,K = list(map(int,input().split()))
P = list(map(int,input().split()))
C = list(map(int,input().split()))
# グルーピング
import copy
P2 = copy.copy(P)
Group = []
while len(P2)>0:
temp = P2[0]
tempGroup = []
while temp in P2:
tempGroup.append(temp)
P2.remove(temp)
temp = P[temp-1]
Group.append(tempGroup)
Point = []
for x in Group:
tempPoint = []
for p in x:
tempPoint.append(C[p-1])
Point.append(tempPoint)
#print(Group)
#print(Point)
max00 = -10**9
for x in Point:
sumx = sum(x)
tempx = copy.copy(x)
tempx.extend(x)
lenx = len(x)
max0 = -10**9
dp = [0]*lenx
if sumx <= 0 or K < lenx:
for i in range(min(lenx-1,K)):
for j in range(lenx):
dp[j] = dp[j] + tempx[j+i]
max0 = max(max0,max(dp))
#print(dp)
else:
K2 = K % lenx
SN = int(K/lenx)
for i in range(lenx):
for j in range(lenx):
dp[j] = dp[j] + tempx[j+i]
#print(dp)
if i < K2:
max0 = max(max0,max(dp) + sumx*SN)
#print(max0)
else:
max0 = max(max0,max(dp) + sumx*(SN-1))
max00 = max(max00,max0)
print(max00)
| def main():
N,K = list(map(int,input().split()))
P = list(map(int,input().split()))
C = list(map(int,input().split()))
# グルーピング
import copy
P2 = set(P)
Group = []
while len(P2)>0:
temp = list(P2)[0]
tempGroup = []
while temp in P2:
tempGroup.append(temp)
P2.remove(temp)
temp = P[temp-1]
Group.append(tempGroup)
Point = []
for x in Group:
tempPoint = []
for p in x:
tempPoint.append(C[p-1])
Point.append(tempPoint)
#print(Group)
#print(Point)
max00 = -10**9
for x in Point:
sumx = sum(x)
tempx = copy.copy(x)
tempx.extend(x)
lenx = len(x)
max0 = -10**9
dp = [0]*lenx
if sumx <= 0 or K < lenx:
for i in range(min(lenx-1,K)):
for j in range(lenx):
dp[j] = dp[j] + tempx[j+i]
max0 = max(max0,max(dp))
#print(dp)
else:
K2 = K % lenx
SN = int(K/lenx)
for i in range(lenx):
for j in range(lenx):
dp[j] = dp[j] + tempx[j+i]
#print(dp)
if i < K2:
max0 = max(max0,max(dp) + sumx*SN)
#print(max0)
else:
max0 = max(max0,max(dp) + sumx*(SN-1))
max00 = max(max00,max0)
print(max00)
if __name__ == "__main__":
main()
| p02585 |
import sys
import resource
sys.setrecursionlimit(10000)
n,k=list(map(int,input().rstrip().split()))
p=list(map(int,input().rstrip().split()))
c=list(map(int,input().rstrip().split()))
def find(start,now,up,max,sum,count,flag):
if start==now:
flag+=1
if start==now and flag==2:
return [max,sum,count]
elif count==up:
return [max,sum,count]
else:
count+=1
sum+=c[p[now-1]-1]
if max<sum:
max=sum
return find(start,p[now-1],up,max,sum,count,flag)
kara=[-10000000000]
for i in range(1,n+1):
m=find(i,i,n,c[p[i-1]-1],0,0,0)
if m[2]>=k:
m=find(i,i,k,c[p[i-1]-1],0,0,0)
if m[0]>kara[0]:
kara[0]=m[0]
elif m[1]<=0:
if m[0]>kara[0]:
kara[0]=m[0]
else:
w=k%m[2]
if w==0:
w=m[2]
spe=find(i,i,w,c[p[i-1]-1],0,0,0)[0]
if m[1]+spe>m[0] and m[1]*(k-w)//m[2]+spe>kara[0]:
kara[0]=m[1]*(k-w)//m[2]+spe
elif m[1]+spe<=m[0] and m[1]*((k-w)//m[2]-1)+m[0]>kara[0]:
kara[0]=m[1]*((k-w)//m[2]-1)+m[0]
print((kara[0])) | import sys
import resource
sys.setrecursionlimit(10000)
n,k=list(map(int,input().rstrip().split()))
p=list(map(int,input().rstrip().split()))
c=list(map(int,input().rstrip().split()))
def find(start,now,up,max,sum,count,flag):
if start==now:
flag+=1
if start==now and flag==2:
return [max,sum,count]
elif count==up:
return [max,sum,count]
else:
count+=1
sum+=c[p[now-1]-1]
if max<sum:
max=sum
return find(start,p[now-1],up,max,sum,count,flag)
kara=[-10000000000]
for i in range(1,n+1):
m=find(i,i,n,c[p[i-1]-1],0,0,0)
if m[2]>=k:
m=find(i,i,k,c[p[i-1]-1],0,0,0)
if m[0]>kara[0]:
kara[0]=m[0]
result=kara[0]
elif m[1]<=0:
if m[0]>kara[0]:
kara[0]=m[0]
result=kara[0]
else:
w=k%m[2]
if w==0:
w=m[2]
spe=find(i,i,w,c[p[i-1]-1],0,0,0)[0]
if m[1]+spe>m[0] and m[1]*(k-w)//m[2]+spe>kara[0]:
kara[0]=m[1]*(k-w)//m[2]+spe
elif m[1]+spe<=m[0] and m[1]*((k-w)//m[2]-1)+m[0]>kara[0]:
kara[0]=m[1]*((k-w)//m[2]-1)+m[0]
result=kara[0]
print(result) | p02585 |
#!/usr/bin/env python3
import sys
from typing import Any, Callable, Deque, Dict, List, Mapping, Optional, Sequence, Set, Tuple, TypeVar, Union
# import time
# import math, cmath
# import numpy as np
# import scipy.sparse.csgraph as cs # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random # random, uniform, randint, randrange, shuffle, sample
# import string # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict # subclass of dict. defaultdict(facroty)
# from collections import Counter # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce # reduce(f, iter[, init])
# from functools import lru_cache # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import _heapify_max, _heappop_max, _siftdown_max
# from heapq import nlargest, nsmallest # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate # accumulate(iter[, f])
# from operator import itemgetter # itemgetter(1), itemgetter('key')
# from fractions import Fraction # Fraction(a, b) => a / b ∈ Q. note: Fraction(0.1) do not returns Fraciton(1, 10). Fraction('0.1') returns Fraction(1, 10)
def main():
Num = Union[int, float]
mod = 1000000007 # 10^9+7
inf = float('inf') # sys.float_info.max = 1.79e+308
# inf = 2 ** 63 - 1 # (for fast JIT compile in PyPy) 9.22e+18
sys.setrecursionlimit(10**6) # 1000 -> 1000000
def input(): return sys.stdin.readline().rstrip()
def ii(): return int(input())
def isp(): return input().split()
def mi(): return map(int, input().split())
def mi_0(): return map(lambda x: int(x)-1, input().split())
def lmi(): return list(map(int, input().split()))
def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
def li(): return list(input())
def debug(x): print(x, file=sys.stderr)
# def _heappush_max(h, item): h.append(item); _siftdown_max(h, 0, len(h)-1)
def calc_score(start):
order = [None] * n
accum = [None] * n
order[start] = 0
accum[start] = 0
place = start
cnt = 0
current_score = 0
M = -inf
while cnt < k:
place = P[place] # 移動
cnt += 1 # 移動回数
current_score += C[place] # 移動後の index でスコアに追加
M = max(M, current_score) # [スタートの次点, 現在地] まで任意の場所をゴールに選ぶときのスコア最大値
if order[place] is None:
# 未訪問
order[place] = cnt
accum[place] = current_score
else:
# 訪問ずみ。loop
head_len = order[place]
loop_len = cnt - head_len
head_score = accum[place]
loop_gain = current_score - accum[place]
if loop_gain <= 0:
# debug('encountered loop, but non-positive loop.')
return M
else:
# debug('encountered positive loop.')
loop_times, res = divmod(k - head_len, loop_len)
# place からスタートして "0 以上" res 以下だけ進むときの
res_score = 0 # 稼ぐ最大スコア
tmp_score = 0 # 現在の累積スコア
tmp_place = place # 現在地
for i in range(res):
tmp_place = P[tmp_place]
tmp_score += C[tmp_place] # 移動後の index でスコアに追加
res_score = max(res_score, tmp_score)
loop_score = head_score + loop_times * loop_gain + res_score
return loop_score
# debug('never encountered loop.')
return M
n, k = mi()
P = lmi_0()
C = lmi()
ans = -inf
for i in range(n):
# debug(ans)
ans = max(ans, calc_score(i))
print(ans)
if __name__ == "__main__":
main()
| #!/usr/bin/env python3
import sys
def main():
# inf = float('inf') # sys.float_info.max = 1.79e+308
inf = 2 ** 63 - 1 # (for fast JIT compile in PyPy) 9.22e+18
sys.setrecursionlimit(10**6) # 1000 -> 1000000
def input(): return sys.stdin.readline().rstrip()
def ii(): return int(input())
def isp(): return input().split()
def mi(): return map(int, input().split())
def mi_0(): return map(lambda x: int(x)-1, input().split())
def lmi(): return list(map(int, input().split()))
def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
def li(): return list(input())
def debug(x): print(x, file=sys.stderr)
def calc_score(start):
order = [None] * n
accum = [None] * n
order[start] = 0
accum[start] = 0
place = start
cnt = 0
current_score = 0
M = -inf
while cnt < k:
place = P[place] # 移動
cnt += 1 # 移動回数
current_score += C[place] # 移動後の index でスコアに追加
M = max(M, current_score) # [スタートの次点, 現在地] まで任意の場所をゴールに選ぶときのスコア最大値
if order[place] is None:
# 未訪問
order[place] = cnt
accum[place] = current_score
else:
# 訪問ずみ (loop)
head_len = order[place]
loop_len = cnt - head_len
head_score = accum[place]
loop_gain = current_score - accum[place]
if loop_gain <= 0:
# debug('encountered loop, but non-positive loop.')
return M
else:
# debug('encountered positive loop.')
loop_times, res = divmod(k - head_len, loop_len)
# place からスタートして "0 以上" res 以下だけ進むときの
res_score = 0 # 稼ぐ最大スコア
tmp_score = 0 # 現在の累積スコア
tmp_place = place # 現在地
for _ in range(res):
tmp_place = P[tmp_place]
tmp_score += C[tmp_place] # 移動後の index でスコアに追加
res_score = max(res_score, tmp_score)
# 限界まで loop を回した上で 0 ~ res だけ貪欲に稼ぐ vs 限界 - 1 回 loop を回し確実にもう一回好きなところでとめられるようにして稼ぐ
loop_score = head_score + loop_times * loop_gain + res_score
stop_score = M + (loop_times - 1) * loop_gain
return max(loop_score, stop_score)
# debug('never encountered loop.')
return M
n, k = mi()
P = lmi_0()
C = lmi()
ans = -inf
for i in range(n):
score = calc_score(i)
# debug(f'start: {i} ans: {score}')
ans = max(ans, score)
print(ans)
if __name__ == "__main__":
main()
| p02585 |
(N, K) = [int(x) for x in input().split()]
P = [int(x) - 1 for x in input().split()] # 0 indexed
C = [int(x) for x in input().split()]
inf = float("inf")
ans = max(C) # at least one move
for pos in range(N):
i = pos
score = 0
cycleLen = None
cycleGain = None
bestInc = 0
for k in range(K):
i = P[i]
score += C[i]
ans = max(ans, score)
bestInc = max(bestInc, score)
if cycleLen is not None and k == K % cycleLen:
numCycles = (K - k) // cycleLen
ans = max(ans, cycleGain * numCycles + bestInc)
break
if i == pos:
cycleLen = k
cycleGain = score
print(ans)
| (N, K) = [int(x) for x in input().split()]
P = [int(x) - 1 for x in input().split()] # 0 indexed
C = [int(x) for x in input().split()]
inf = float("inf")
ans = max(C) # at least one move
for pos in range(N):
i = pos
score = 0
cycleLen = None
cycleGain = None
bestInc = 0
k = 0
while k < K:
i = P[i]
score += C[i]
ans = max(ans, score)
if i == pos:
cycleLen = k + 1
numCycles = max(0, (K - k - cycleLen) // cycleLen)
if k + numCycles * cycleLen < K:
k += numCycles * cycleLen
score += numCycles * score
k += 1
print(ans)
| p02585 |
from collections import deque
import sys, copy,itertools
input = sys.stdin.readline
n, k = list(map(int,input().split()))
P = list(map(int,input().split()))
C = list(map(int,input().split()))
POINT = [[-10**12 for i in range(n)] for j in range(k)]
PLACE = [[0 for i in range(n)] for j in range(k)]
for i in range(n):
POINT[0][i] = C[P[i]-1]
PLACE[0][i] = P[i]-1 #P[i]は1スタートなのでずれる
#A[0][i] = C[P[i]]
#print(PLACE)
#print(POINT)
tempmax= max(POINT[0])
for j in range(1,k): #日付
for i in range(n):
PLACE[j][i]=P[PLACE[j-1][i]]-1
POINT[j][i]=POINT[j-1][i] + C[PLACE[j][i]]
tempmax = max(tempmax,POINT[j][i])
#print(PLACE)
#print(POINT)
print(tempmax) | from collections import deque
import sys, copy,itertools
input = sys.stdin.readline
n, k = list(map(int,input().split()))
#P = list(map(int,input().split()))
P = list([int(x) - 1 for x in input().split()]) #ひとつづつずらす
C = list(map(int,input().split()))
SCORE = [0]*(n+1)
max_score = -10**12
for i in range(n):
x = i
TEMPMAX = [-10**9] * (n+1)
for j in range(1, n+1):
SCORE[j] = SCORE[j-1] + C[P[x]]
TEMPMAX[j]= max(TEMPMAX[j-1], SCORE[j])
x = P[x]
if x == i:
break
if j >= k:
max_score = max(max_score,TEMPMAX[k])
elif SCORE[j] < 0:
max_score = max(max_score, TEMPMAX[j])
else:
m = k//j
a = SCORE[j] *(m-1) + TEMPMAX[j]
b = SCORE[j] *m + TEMPMAX[k % j]
max_score = max(max_score, a, b)
print(max_score) | p02585 |
import sys
input = sys.stdin.readline
n, k = list(map(int, input().split()))
p = list(map(int, input().split()))
p = [0] + p
c = list(map(int, input().split()))
c = [0] + c
score = [[0] * (n + 1) for _ in range(n + 1)]
# score[i][j]: iからstartしてj回移動した時のスコア
l_cycle = [0] * (n + 1)
for i in range(1, n + 1):
start = i
move_cnt = 0
nxt = i
while move_cnt < n:
nxt = p[nxt]
score[i][move_cnt + 1] += score[i][move_cnt] + c[nxt]
move_cnt += 1
if nxt == start:
l_cycle[start] = move_cnt
break
# for i in range(1, n + 1):
# print(score[i])
# print('l_cycle', l_cycle)
ans = -float('inf')
for s in range(1, n + 1):
if k <= l_cycle[s]:
# サイクルを回らないので
temp = max(score[s][1:k + 1])
ans = max(ans, temp)
continue
# 以降は一周以上出来る時
# 一周以下でやめる場合を探索
temp = max(score[s][1:l_cycle[s] + 1])
ans = max(ans, temp)
# if score[s][l_cycle[s]] <= 0:
# # 周回する意味がない
# continue
sk = k // l_cycle[s] # 何周出来るか
remk = k % l_cycle[s]
temp = sk * score[s][l_cycle[s]] # 周回によるスコア
if remk != 0:
temp += max(score[s][1:remk + 1])
ans = max(ans, temp)
print(ans)
| n, k = list(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 = -float('inf')
for st in range(n):
x = st
score = []
tot = 0
while True:
x = p[x]
score.append(c[x])
tot += c[x]
if x == st:
break
l = len(score)
now = 0
t = 0
for i in range(l):
t += score[i]
if i + 1 > k:
break
now = t
if tot > 0:
cycle_num = (k - (i + 1)) // l
now += tot * cycle_num
ans = max(ans, now)
print(ans)
| p02585 |
from itertools import accumulate
def main():
cells, moves = [int(x) for x in input().split()]
jumps_from = [int(x) - 1 for x in input().split()]
score_on = [int(x) for x in input().split()]
ans = - 10**10
for start in range(cells):
route = []
route_append = route.append
position = start
while True:
route_append(score_on[position])
position = jumps_from[position]
if position == start: # Looped
break
length = len(route)
total = sum(route)
accum_tmp = 0
for i, score in enumerate(route):
accum_tmp += score
if i + 1 > moves:
break
accum = accum_tmp
if total > 0:
accum += total * ((moves - (i + 1)) // length)
ans = max(ans, accum)
# if total > 0:
# q, mod = divmod(moves, length)
# if mod == 0:
# candidate = total * q
# else:
# candidate = max(list(accumulate(route))[:mod]) + total * q
# else:
# candidate = max(list(accumulate(route))[:min(moves, length)])
# ans = max(ans, candidate)
return ans
if __name__ == '__main__':
ans = main()
print(ans)
| def main():
cells, can_jump = [int(x) for x in input().split()]
jumps_from = [int(x) - 1 for x in input().split()]
score_on = [int(x) for x in input().split()]
ans = - 10**10
for start in range(cells):
route = []
position = start
while True:
route.append(score_on[position])
position = jumps_from[position]
if position == start: # Looped
break
length = len(route)
total = sum(route)
accum_tmp = 0
for jumping, score in enumerate(route):
accum_tmp += score
if jumping + 1 > can_jump:
break
accum = accum_tmp
if total > 0:
accum += total * ((can_jump - (jumping + 1)) // length)
ans = max(ans, accum)
return ans
if __name__ == '__main__':
ans = main()
print(ans)
| p02585 |
n, k = list(map(int, input().split()))
P = [*[int(x)-1 for x in input().split()]]
C = [*list(map(int, input().split()))]
INF = 10**18
score = -INF
for st in range(n):
tot = 0 # cost of one lap
costs = []
nx = st
while True:
nx = P[nx]
costs.append(C[nx])
tot += C[nx]
if nx == st: break
lap_c = -INF # lap costs
r = k
if tot >= 0:
nl, r = divmod(k, len(costs)) # number of loops
lap_c = max(lap_c, tot * nl)
# print('nl {}, k {}'.format(nl, k))
sum_c = 0
max_c = -INF
for c in costs[:min(r, len(costs))]:
sum_c += c
max_c = max(max_c, sum_c)
score = max(score, lap_c, max_c, lap_c + max_c)
# print(st, costs, tot)
# print(lap_c, max_c, lap_c+max_c, '=', score)
print(score)
# print('===')
# print(n,k)
# print(P)
# print(C,end='\n\n')
| n, k = list(map(int, input().split()))
P = [*[int(x)-1 for x in input().split()]]
C = [*list(map(int, input().split()))]
INF = 10**18
max_score = -INF
for st in range(n):
lc = 0 # lap count
lap_sc = 0 # lap score
nx = st
while True:
lc += 1
lap_sc += C[nx]
nx = P[nx]
if nx == st: break
sum_sc = 0
kc = 0
while True:
kc += 1
if k < kc: break
sum_sc += C[nx]
score = sum_sc + max(0, lap_sc) * ((k - kc) // lc)
max_score = max(max_score, score)
nx = P[nx]
if nx == st: break
print(max_score)
# print('===')
# print(n,k)
# print(P)
# print(C,end='\n\n')
| p02585 |
n, k = list(map(int, input().split()))
P = [*[int(x)-1 for x in input().split()]]
C = [*list(map(int, input().split()))]
score = -10**18
for st in range(n):
lap_cn = 0
lap_sc = 0
nx = st
while True:
lap_cn += 1
lap_sc += C[nx]
nx = P[nx]
if nx == st: break
lap_sc = max(0, lap_sc)
sum_sc = 0
for k_cn in range(k):
sum_sc += C[nx]
score = max(score, sum_sc + lap_sc * ((k - (k_cn + 1)) // lap_cn))
nx = P[nx]
if nx == st: break
print(score)
| n, k = list(map(int, input().split()))
P = [*[int(x)-1 for x in input().split()]]
C = [*list(map(int, input().split()))]
score = -10**18
for st in range(n):
lap_cn = lap_sc = sum_sc = 0
nx = st
while True:
lap_cn += 1
lap_sc += C[nx]
nx = P[nx]
if nx == st: break
lap_sc = max(0, lap_sc)
for k_cn in range(1, k+1):
sum_sc += C[nx]
score = max(score, sum_sc + lap_sc * ((k - k_cn) // lap_cn))
nx = P[nx]
if nx == st: break
print(score)
| p02585 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.