Problem:


Score : 500 points

Problem Statement

There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i.

Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, j), he can move to (i + 1, j) or (i, j + 1) (but cannot move to a non-existent square).

He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits.

Find the maximum possible sum of the values of items he picks up.

Constraints

1 \leq R, C \leq 3000

1 \leq K \leq \min(2 \times 10^5, R \times C)

1 \leq r_i \leq R

1 \leq c_i \leq C

(r_i, c_i) \neq (r_j, c_j) (i \neq j)

1 \leq v_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

R C K
r_1 c_1 v_1
r_2 c_2 v_2
:
r_K c_K v_K

Output

Print the maximum possible sum of the values of items Takahashi picks up.

Sample Input 1

2 2 3
1 1 3
2 1 4
1 2 5

Sample Output 1

8

He has two ways to get to the goal:

Visit (1, 1), (1, 2), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 5 = 8.

Visit (1, 1), (2, 1), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 4 = 7.

Thus, the maximum possible sum of the values of items he picks up is 8.

Sample Input 2

2 5 5
1 1 3
2 4 20
1 2 1
1 3 4
1 4 2

Sample Output 2

29

We have four items in the 1-st row. The optimal choices are as follows:

Visit (1, 1) (1, 2), (1, 3), (1, 4), (2, 4), and (2, 5), in this order, and pick up all items except the one on (1, 2). Then, the total value of the items he picks up will be 3 + 4 + 2 + 20 = 29.

Sample Input 3

4 5 10
2 5 12
1 5 12
2 3 15
1 2 20
1 1 28
2 4 26
3 2 27
4 5 21
3 5 10
1 3 10

Sample Output 3

142



Sample input:
2 2 3
1 1 3
2 1 4
1 2 5


Sample output:
8

Submission status: Runtime Error

Solution code:
# 入力
R, C, K = map(int, input().split())
point_map = [[0 for _ in range(C+1)] for _ in range(R+1)]
max_point = [[[0 for _ in range(4)] for _ in range(C + 1)]
             for _ in range(R + 1)]
maxmax_point = [[0 for _ in range(C + 1)] for _ in range(R + 1)]


for i in range(K):
    _r, _c, _k = map(int, input().split())
    point_map[_r][_c] = _k

for i in range(1, R+1):
    itemss = [[]]
    for j in range(1, C + 1):
        point = point_map[i][j]
        max_point[i][j][0] = max(
            max_point[i][j - 1][0], maxmax_point[i - 1][j])
        if point == 0:
            for n in range(1, 4):
                max_point[i][j][n] = max_point[i][j - 1][n]
        else:
            itemss = [[]] + [items + [point]
                             for items in itemss]  # items[1] アイテム一つ
            itemss_len = len(itemss)

            for n in range(1, min(itemss_len, 4)):
                max_point[i][j][n] = max_point[i][j - 1][n - 1] + point

            max_point[i][j][1] = max(
                max_point[i][j][1], maxmax_point[i - 1][j]+point)

            if itemss_len > 4:
                items = itemss[4][:]  # 4 こアイテムがあるやつ
                del_item = min(items)
                items.remove(del_item)
                sa = max_point[i][j - 1][4]-del_item
                if sa > max_point[i][j - 1][3]:
                    max_point[i][j][3] = sa + point
                    itemss = itemss[:3] + items
                else:
                    itemss = itemss[:4]
        # [print(i, j, n, max_point[i][j][n])
        # for n in range(min(len(itemss), 4))]
        maxmax_point[i][j] = max(max_point[i][j])
        # print(i, j, maxmax_point[i][j])

print(maxmax_point[R][C])

Submission status: Runtime Error

Solution code:
def main():
    c=[[0]*3001for _ in range(3001)]
    h,w,k=map(int,input().split())
    for i in range(k):
        y,x,v=map(int,input().split())
        c[y][x]=v
    dp=[[0]*(w+1)for _ in range(h+1)]
    for i in range(1,h+1):
        x=y=z=p=0
        for j in range(1,w+1):
            v=c[i][j]
            if v>x:x,y,z=v,x,y
            elif v>y:y,z=v,y
            elif v>z:z=v
            if x+y+z+p<=dp[i-1][j]+v:
                x,y,z=v,0,0
                p=dp[i-1][j]
            dp[i][j]=x+y+z+p
    a=dp[h][w]
    dp=[[[0]*(w+1)for _ in range(h+1)]for _ in range(4)]
    for i in range(1,h+1):
        for j in range(1,w+1):
            x=max(dp[0][i-1][j],dp[1][i-1][j],dp[2][i-1][j],dp[3][i-1][j])
            for k in range(4):
                if k:dp[k][i][j]=max(dp[k][i][j-1],dp[k-1][i][j-1]+c[i][j])
                else:dp[k][i][j]=max(dp[k][i][j-1],x)
            dp[1][i][j]=max(dp[1][i][j],x+c[i][j])
    if a<max(dp[0][h][w],dp[1][h][w],dp[2][h][w],dp[3][h][w]):1/0
    else:print(a)
main()

Submission status: Runtime Error

Solution code:
# 入力
R, C, K = map(int, input().split())
point_map = [[0 for _ in range(C+1)] for _ in range(R+1)]
max_point = [[[0 for _ in range(4)] for _ in range(C + 1)]
             for _ in range(R + 1)]
maxmax_point = [[0 for _ in range(C + 1)] for _ in range(R + 1)]


for i in range(K):
    _r, _c, _k = map(int, input().split())
    point_map[_r][_c] = _k

for i in range(1, R+1):
    itemss = [[]]
    for j in range(1, C + 1):
        point = point_map[i][j]
        max_point[i][j][0] = max(
            max_point[i][j - 1][0], maxmax_point[i - 1][j])
        if point == 0:
            for n in range(1, 4):
                max_point[i][j][n] = max_point[i][j - 1][n]
        else:
            itemss = [[]] + [items + [point]
                             for items in itemss]  # items[1] アイテム一つ
            itemss_len = len(itemss)
            for n in range(1, min(itemss_len, 4)):
                max_point[i][j][n] = max_point[i][j - 1][n - 1] + point

            max_point[i][j][1] = max(
                max_point[i][j][1], maxmax_point[i - 1][j]+point)

            if itemss_len > 4:
                items = itemss[4][:]  # 4 こアイテムがあるやつ
                del_item = min(items)
                items.remove(del_item)
                sa = max_point[i][j - 1][3]-del_item
                if sa > max_point[i][j - 1][n - 1]:
                    max_point[i][j][3] = sa + point
                    itemss = itemss[:3] + itemss[-1]
                else:
                    itemss = itemss[:4]
        # [print(i, j, n, max_point[i][j][n])
        # for n in range(min(len(itemss), 4))]
        maxmax_point[i][j] = max(max_point[i][j])
        # print(i, j, maxmax_point[i][j])

print(maxmax_point[R][C])

Submission status: Runtime Error

Solution code:
def main():
    c=[[0]*3001for _ in range(3001)]
    h,w,k=map(int,input().split())
    for i in range(k):
        y,x,v=map(int,input().split())
        c[y][x]=v
    dp=[[0]*(w+1)for _ in range(h+1)]
    for i in range(1,h+1):
        x=y=z=p=0
        for j in range(1,w+1):
            v=c[i][j]
            if v>x:x,y,z=v,x,y
            elif v>y:y,z=v,y
            elif v>z:z=v
            if x+y+z+p<=dp[i-1][j]+v:
                x,y,z=v,0,0
                p=dp[i-1][j]
            dp[i][j]=x+y+z+p
    a=dp[h][w]
    dp=[[[0]*(w+1)for _ in range(h+1)]for _ in range(4)]
    for i in range(1,h+1):
        for j in range(1,w+1):
            x=max(dp[0][i-1][j],dp[1][i-1][j],dp[2][i-1][j],dp[3][i-1][j])
            for k in range(4):
                if k:dp[k][i][j]=max(dp[k][i][j-1],dp[k-1][i][j-1]+c[i][j])
                else:dp[k][i][j]=max(dp[k][i][j-1],x)
            dp[1][i][j]=max(dp[1][i][j],x+c[i][j])
    if a<max(dp[0][h][w],dp[1][h][w],dp[2][h][w],dp[3][h][w]):1/0
main()

Submission status: Runtime Error

Solution code:
R, C, K=map(int, input().split())
math=[[0]*C for _ in range(R)]
for _ in range(K):
  r, c, v=map(int, input().split())
  math[r-1][c-1]=v
  
dp=[[[0]*C for __ in range(R)] for _ in range(4)]
if math[0][0]>0:
  dp[1][0][0]=math[0][0]+0
  
for j in range(1, C):
  dp[0][0][j]=dp[0][j-1][0]+0
  dp[1][0][j]=max(dp[1][0][j-1], dp[0][0][j-1]+math[0][j])
  dp[2][0][j]=max(dp[2][0][j-1], dp[1][0][j-1]+math[0][j])
  dp[3][0][j]=max(dp[3][0][j-1], dp[2][0][j-1]+math[0][j])
    
for i in range(1, R):
  dp[0][i][0]=max(dp[0][i-1][0], dp[1][i-1][0], dp[2][i-1][0], dp[3][i-1][0])
  dp[1][i][0]=dp[0][i][0]+math[i][0]
  for j in range(1, C):
    dp[0][i][j]=max(dp[0][i][j-1], max(dp[0][i-1][j], dp[1][i-1][j], dp[2][i-1][j], dp[3][i-1][j]))
    dp[1][i][j]=max(dp[1][i][j-1], dp[0][i][j-1]+math[i][j], max(dp[0][i-1][j], dp[1][i-1][j], dp[2][i-1][j], dp[3][i-1][j])+math[i][j])
    dp[2][i][j]=max(dp[2][i][j-1], dp[1][i][j-1]+math[i][j])
    dp[3][i][j]=max(dp[3][i][j-1], dp[2][i][j-1]+math[i][j])
    
print(max(dp[0][-1][-1], dp[1][-1][-1], dp[2][-1][-1], dp[3][-1][-1]))

Submission status: Runtime Error

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

v = [[0 for _ in range(c)]for __ in range(r)]
for _ in range(k):
    ri,ci,vi = map(int,input().split())
    v[ri-1][ci-1] = vi

dp = [[[0 for _ in range(c+5)]for __ in range(r+5)]for ___ in range(4)]


for h in range(r):
    for w in range(c):
        for k in range(2,-1,-1):
            dp[k+1][h][w] = max(dp[k+1][h][w], dp[k][h][w] + v[h][w])

        for k in range(4):
            dp[h+1][w][0] = max(dp[h+1][w][0],dp[h][w][k])
            dp[h][w+1][k] = max(dp[h][w+1][k],dp[h][w][k])

ans = 0
for i in range(4):
    ans = max(ans, dp[i][r-1][c-1])
print(ans)

Submission status: Runtime Error

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

ansMap = [ [ [0,[]] for i in range(c + 1) ] for j in range(r + 1) ]

itemList = [ [0 for i in range(c + 1)] for j in range(r + 1) ]

for i in range(k):
    ri,ci,ki = list(map(int,input().split()))
    itemList[ri][ci] = ki

item = itemList[1][1]
#if item > 0:
#    ansMap[1][1][0] = item
#    ansMap[1][1][1].append(item)

for i in range(1,r+1):
    for j in range(0,c):
        item = itemList[i][j+1]
        if ansMap[i][j][0] <= ansMap[i-1][j+1][0]:
            ansMap[i][j+1][0] = ansMap[i-1][j+1][0]
            if item != 0:
                ansMap[i][j+1][0] += item
                ansMap[i][j+1][1].append(item)
        elif item != 0:
            if len(ansMap[i][j][1]) < 3:
                ansMap[i][j+1][0] = ansMap[i][j][0] + item
                ansMap[i][j+1][1] = ansMap[i][j][1].copy()
                ansMap[i][j+1][1].append(item)
            elif min(ansMap[i][j][1]) < item:
                if ansMap[i][j][0] - min(ansMap[i][j][1]) < ansMap[i-1][j+1][0]:
                    ansMap[i][j+1][0] = ansMap[i-1][j+1][0]
                else:
                    ansMap[i][j+1][0] = ansMap[i][j][0] + item - min(ansMap[i][j][1])
                    ansMap[i][j+1][1] = ansMap[i][j][1].copy()
                    ansMap[i][j+1][1].remove(min(ansMap[i][j+1][1]))
                    ansMap[i][j+1][1].append(item)
            else:
                if ansMap[i][j][0] <= ansmap[i-1][j+1][0] + item:
                    ansMap[i][j+1][0] = ansMap[i-1][j+1][0] + item
                    ansMap[i][j+1][1].append(item)
                else:
                    ansMap[i][j+1][0] = ansMap[i][j][0] + item
                    ansMap[i][j+1][1] = ansMap[i][j][1].copy()
                    ansMap[i][j+1][1].append(item)
        else:
            ansMap[i][j+1][0] = ansMap[i][j][0]
            ansMap[i][j+1][1] = ansMap[i][j][1].copy()

#print(ansMap)
print(ansMap[r][c][0])

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
def main()
    (R, C, K), *D = [[*map(int,o.split())] for o in open(0)]
    D = {(r - 1, c - 1) : v for r, c, v in D}

    dp = [[[-1] * 4 for _ in [None] * C] for _ in [None] * R]

    dp[0][0][0] = 0
    for r in range(R):
        for c in range(C):
            v = D.get((r, c), None)
            for i in range(4):
                if dp[r][c][i] > -1:
                    if r < R - 1:
                        dp[r + 1][c][0] = max(dp[r + 1][c][0], dp[r][c][i])
                    if c < C - 1:
                        dp[r][c + 1][i] = max(dp[r][c + 1][i], dp[r][c][i])
                    if i < 3 and v:
                        if r < R - 1:
                            dp[r + 1][c][0] = max(dp[r + 1][c][0], dp[r][c][i] + v)
                        if c < C - 1:
                            dp[r][c + 1][i + 1] = max(dp[r][c + 1][i + 1], dp[r][c][i] + v)

    v = D.get((R - 1, C - 1), 0)
    ans = dp[R - 1][C - 1][3]
    for i in range(3):
        ans = max(ans, dp[R - 1][C - 1][i] + v)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys, math
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from itertools import combinations, permutations, product
from heapq import heappush, heappop
from functools import lru_cache
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 1000000007
sys.setrecursionlimit(1000000)

import numpy as np

R, C, K = rl()
#I = [[0]*(C+2) for _ in range(R+2)]
I = np.zeros([R+2, C+2], dtype=int)
for i in range(K):
	r, c, v = rl()
	I[r][c] = v
 
#dp = [[[0 for _ in range(C+2)] for _ in range(R+2)] for _ in range(4)]
dp = np.zeros([4,R+2,C+2], dtype=int)

for i in range(R+1):
	for j in range(C+1):
		for m in range(4):
			ni, nj = i, j+1
			dp[m][ni][nj] = max(dp[m][ni][nj], dp[m][i][j])
			if m < 3:
				dp[m+1][ni][nj] = max(dp[m+1][ni][nj], dp[m][i][j]+I[ni][nj])
			ni, nj = i+1, j
			dp[0][ni][nj] = max(dp[0][ni][nj], dp[m][i][j])
			dp[1][ni][nj] = max(dp[1][ni][nj], dp[m][i][j]+I[ni][nj])
ans = 0
for m in range(4):
	ans = max(ans, dp[m][R][C])
print(ans)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.buffer.readline
R,C,K = map(int,input().split())
goods = [[0]*(C+1) for _ in range(R+1)]
INF = 10**18
for i in range(K):
    ri,ci,vi = map(int,input().split())
    goods[ri][ci] = vi
DP = [[[-INF]*(C+1) for _ in range(R+1)] for _ in range(4)]
DP[0][1][1] = 0
if goods[1][1]:
    DP[1][1][1] = goods[1][1]
for j in range(1,C):
    DP[0][1][j+1] = 0
    if goods[1][j+1]:
        DP[1][1][j+1] = max(DP[1][1][j],DP[0][1][j]+goods[1][j+1])
        DP[2][1][j+1] = max(DP[2][1][j],DP[1][1][j]+goods[1][j+1])
        DP[3][1][j+1] = max(DP[3][1][j],DP[2][1][j]+goods[1][j+1])
    else:
        DP[1][1][j+1] = DP[1][1][j]
        DP[2][1][j+1] = DP[2][1][j]
        DP[3][1][j+1] = DP[3][1][j]
for i in range(1,R):
    DP[0][i+1][1] = max(DP[0][i][1],DP[1][i][1],DP[2][i][1],DP[3][i][1])
    if goods[1][i+1]:
        DP[1][i+1][1] = DP[0][i+1][1] + goods[i+1][1]
for i in range(2,R+1):
    for j in range(2,C+1):
        DP[0][i][j] = max(DP[0][i-1][j],DP[1][i-1][j],DP[2][i-1][j],DP[3][i-1][j],DP[0][i][j-1])
        if goods[i][j]:
            DP[1][i][j] = max(DP[0][i][j]+goods[i][j],DP[1][i][j-1])
            DP[2][i][j] = max(DP[2][i][j-1],DP[1][i][j-1]+goods[i][j])
            DP[3][i][j] = max(DP[3][i][j-1],DP[2][i][j-1]+goods[i][j])
        else:
            DP[1][i][j] = DP[1][i][j-1]
            DP[2][i][j] = DP[2][i][j-1]
            DP[3][i][j] = DP[3][i][j-1]
print(max(DP[0][R][C],DP[1][R][C],DP[2][R][C],DP[3][R][C]))

Submission status: Runtime Error

Solution code:
import sys
import queue

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(tin())
mod=1000000007

#+++++

def rc_to_s(r,c):
	return str(r)+'_'+str(c)
	
def s_to_rc(s):
	r,c = map(int, s.split('_'))
	return r, c
	
class qqq:
	def __init__(self):
		self.l=[]
		self.sum=0
		self.num=0
	
	def update(v):
		if self.num==3 and v > self.l[0]:
			self.l[0]=v
			self.l.sort()
			self.sum=sum(self.l)
		elif self.num < 3:
			self.l.append(v)
			self.sum += v
			self.num += 1
			
def main():
	#a = int(input())
	r, c, k = tin()
	#s = input()
	dd={}
	for _ in range(k):
		ri, ci, vi = tin()
		dd[rc_to_s(ri-1,ci-1)]=vi
	
	cv=[0]*c

	pq=qqq()
	npq=0
	vpq=0
	for ci in range(c):
		ps = rc_to_s(0, ci)
		if ps in dd:
			tv=dd[ps]
			pq.update(tv)
		cv[ci]=pq.sum
		
	for ri in range(1, r):
		ncv = [0]*c
		for ci in range(c):
			if ci == 0 or ncv[ci-1] <= cv[ci]:
				pq=qqq()
				ovpq=cv[ci]	
			ps = rc_to_s(ri, ci)
			if ps in dd:
				tv=dd[ps]
				pq.update(tv)

			ncv[ci]=ovpq + pq.sum
		cv=ncv
		#pa(cv)
	return cv[-1]

			
		
		
	
	
	

		
	
	
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Runtime Error

Solution code:
from sys import stdin,setrecursionlimit
import numpy as np
setrecursionlimit(1000000)
input=stdin.readline
n,m,ss=map(int,input().split())
mat=[[0]*m for i in range(n)]
for i in range(ss):
    x,y,v=map(int,input().split())
    mat[x-1][y-1]+=v
dp=np.zeros([n,m,4],dtype="int64")
for i in range(n):
    for j in range(m):
        for k in range(4):
            dp[i][j][k]=-1
l=3
def dfs(x,y,k):
    if x<0 or y<0 or x>=n or y>=m:
        return 0
    if dp[x][y][k]!=-1:
        return dp[x][y][k]
    if k>0:
        dp[x][y][k]=max(mat[x][y]+dfs(x+1,y,l),mat[x][y]+dfs(x,y+1,k-1),dfs(x,y+1,k),dfs(x+1,y,l))
    else:
        dp[x][y][k]=max(dfs(x+1,y,l),dfs(x,y+1,k))
    return dp[x][y][k]

print(dfs(0,0,l))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub


import sys
sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(R, C, K, RCV):

    V = [[0] * C for _ in range(R)]
    for r, c, v in RCV:
        V[r-1][c-1] = v

    memo = [[[0] * 4 for _ in range(C+1)] for __ in range(R+1)]

    for i in range(R):
        for j in range(C):
            for p in range(4):
                memo[i][j+1][p] = max(memo[i][j+1][p], memo[i][j][p])
                memo[i+1][j][0] = max(memo[i+1][j][0], memo[i][j][p])
                memo[i][j+1][p+1] = max(memo[i][j+1][p+1], memo[i][j][p] + V[i][j])
                memo[i+1][j][0] = max(memo[i+1][j][0], memo[i][j][p] + V[i][j])

    return max(memo[R-1][C])

def main():
    R, C, K = read_int_n()
    RCV = [read_int_n() for _ in range(K)]
    print(slv(R, C, K, RCV))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from sys import stdin
input=stdin.readline
n,m,ss=map(int,input().split())
mat=[[0]*m for i in range(n)]
for i in range(ss):
    x,y,v=map(int,input().split())
    mat[x-1][y-1]+=v
dp=[[[-1]*4 for i in range(m)] for j in range(n)]
l=3
def dfs(x,y,k):
    if x<0 or y<0 or x>=n or y>=m:
        return 0
    if dp[x][y][k]!=-1:
        return dp[x][y][k]
    if k>0:
        dp[x][y][k]=max(mat[x][y]+dfs(x+1,y,l),mat[x][y]+dfs(x,y+1,k-1),dfs(x,y+1,k),dfs(x+1,y,l))
    else:
        dp[x][y][k]=max(dfs(x+1,y,l),dfs(x,y+1,k))
    return dp[x][y][k]

print(dfs(0,0,l))

Submission status: Runtime Error

Solution code:
import sys
input=sys.stdin.readline
def main():
    r,c,k=map(int,input().split())
    v=dict()
    for _ in range(k):
        ri,ci,a=map(int,input().split())
        ri-=1
        ci-=1
        v[(ri,ci)]=a
    dp=[[[0]*c for _ in range(r)] for i in range(4)]
    #print(dp)
    if (0,0) in v:
        if v[(0,0)]>0:
            dp[0][0][1]=v[(0,0)]
    for i in range(r):
        for j in range(c):
            if i>0:
                if (i,j) in v:
                    if v[(i,j)]>0:
                        for k in range(min(3,j+1)+1):
                            dp[1][i][j]=max(dp[1][i][j],dp[k][i-1][j]+v[(i,j)])
                for k in range(4):
                    dp[k][i][j]=max(dp[k][i][j],dp[k][i-1][j])
            if j>0:
                if (i,j) in v:
                    if v[(i,j)]>0:
                        for k in range(min(3,j+1)+1):
                            if k>0:
                                dp[k][i][j]=max(dp[k][i][j],dp[k-1][i][j-1]+v[(i,j)])
                for k in range(4):
                    dp[k][i][j]=max(dp[k][i][j],dp[k][i][j-1])
    #print(dp)
    ans=0
    for i in range(4):
        ans=max(dp[i][r-1][c-1],ans)
    return print(ans)
if __name__=="__main__":
    main()

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
P = list(map(lambda x:int(x)-1, input().split()))
C = list(map(int, input().split()))
done = [False] * N
ans = -10**30
must_negative = all([c < 0 for c in C])
for i in range(N):
  if done[i]:
    continue
  loop = [i]
  done[loop[-1]] = True
  while not done[P[loop[-1]]]:
    loop.append(P[loop[-1]])
    done[loop[-1]] = True
    #print(loop, done)
  #print(loop)
  scores = [C[i] for i in loop]
  #print(scores)
  cumsum = [0]
  for s in scores * 2:
    cumsum.append(cumsum[-1] + s)
  #print(cumsum)
  L = len(scores)
  if cumsum[L] >= 0:
    # (L+K) // L  loops - max
    l = max(0, (K - L) // L )
    k_max = K - l * L
    #print(l, k_max)
    base_score = cumsum[L] * l
  else:
    k_max = min(K, L)
    #print(k_max)
    base_score = 0
  for i in range(L):
    for k in range(k_max+1):
      score = base_score + cumsum[i + k] - cumsum[i]
      #print(i, k, base_score, score)
      if must_negative and score == 0:
        continue
      ans = max(ans, score)
print(ans)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
input().rstrip() # remove last '\n'

def main():
    r,c,k = map(int, input().split())
    rcv = [ [0]*c for _ in range(r) ]

    for _ in range(k):
        ri,ci,vi = map(int, input().split())
        rcv[ri-1][ci-1] = vi

    # dp[0] = [ [0]*c for _ in range(r) ]
    # dp1 = [ [0]*c for _ in range(r) ]
    # dp2 = [ [0]*c for _ in range(r) ]
    # dp[3] = [ [0]*c for _ in range(r) ]
    dp = [ [ [0]*c  for _ in range(r) ] for _ in range(4) ]


    dp[1][0][0] = rcv[0][0]
    for i in range(r):
        for j in range(c):
            if i+1 < r:
                dp[0][i+1][j] = max(dp[0][i][j], dp[1][i][j], dp[2][i][j], dp[3][i][j], dp[0][i+1][j])
                if rcv[i+1][j] > 0:
                    dp[1][i+1][j] = max(dp[1][i+1][j],  max(dp[0][i][j], dp[1][i][j], dp[2][i][j], dp[3][i][j])+rcv[i+1][j])

            if j+1 < c:
                dp[0][i][j+1] = max(dp[0][i][j], dp[0][i][j+1])
                dp[1][i][j+1] = max(dp[1][i][j], dp[1][i][j+1])
                dp[2][i][j+1] = max(dp[2][i][j], dp[2][i][j+1])
                dp[3][i][j+1] = max(dp[3][i][j], dp[3][i][j+1])
                if rcv[i][j+1] > 0:
                    dp[1][i][j+1] = max(dp[1][i][j+1], dp[0][i][j]+rcv[i][j+1])
                    dp[2][i][j+1] = max(dp[2][i][j+1], dp[1][i][j]+rcv[i][j+1])
                    dp[3][i][j+1] = max(dp[3][i][j+1], dp[2][i][j]+rcv[i][j+1])

    ans = max(dp[0][r-1][c-1], dp[1][r-1][c-1], dp[2][r-1][c-1], dp[3][r-1][c-1])
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
R, C, K = map(int, input().split())
rcvs = [tuple(map(int, input().split())) for _ in range(K)]

rcvs.sort(key = lambda t: t[1] * 30000 + t[0])

dp = [[0] * (R+1) for _ in range(4)]
index = 0
for c in range(C+1):
    while index < K and rcvs[index][1] == c:
        x, _, v = rcvs[index]
        if dp[3][x] < dp[2][x] + v:
            dp[3][x] = dp[2][x] + v
        if dp[2][x] < dp[1][x] + v:
            dp[2][x] = dp[1][x] + v
        if dp[1][x] < dp[0][x] + v:
            dp[1][x] = dp[0][x] + v
        if dp[0][x+1] < max((dp[i][x] + v for i in range(4))):
            dp[0][x+1] = max((dp[i][x] + v for i in range(4)))
        index += 1
        #print(dp)   
    
print(max(max(row) for row in dp))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub


import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(R, C, K, RCV):

    V = [[0] * C for _ in range(R)]
    for r, c, v in RCV:
        V[r-1][c-1] = v

    @lru_cache(maxsize=None)
    def f(i, j, p):
        if i >= R or j >= C:
            return 0
        r = 0
        r = max(r, f(i+1, j, 0))
        r = max(r, f(i, j+1, p))
        if V[i][j] != 0 and p < 3:
            r = max(r, f(i+1, j, 0) + V[i][j])
            r = max(r, f(i, j+1, p+1) + V[i][j])
        return r
    return f(0, 0, 0)


def main():
    R, C, K = read_int_n()
    RCV = [read_int_n() for _ in range(K)]
    print(slv(R, C, K, RCV))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys

inp = [int(x) for x in sys.stdin.read().split()]; ii = 0

rows, cols, k = inp[ii:ii+3]; ii += 3
items = [[] for _ in range(rows+1)]
best = [0]*(cols+1)
for _ in range(k):
	inp[ii:ii+3]; ii += 3
	items[r].append([c, v])
for i in range(rows+1):
	items[i].sort()
ans = 0
for r in range(1, rows+1):
	dp = []
	best1, best2 = 0, 0
	Row = items[r]
	for c, v in Row:
		v1 = best[c] + v
		v2 = best1 + v
		v3 = best2 + v
		V = v1
		if V < v2:
			V = v2
		if V < v3:
			V = v3
		dp.append(V)
		if v1 > best1:
			best1 = v1
		if v2 > best2:
			best2 = v2
		if ans < V:
			ans = V
	for j in range(len(dp)):
		if best[Row[j][0]] < dp[j]:
			best[Row[j][0]] = dp[j]
	for j in range(2, cols+1):
		if best[j] < best[j-1]:
			best[j] = best[j-1]
print(ans)

Submission status: Runtime Error

Solution code:
import sys

inp = [int(x) for x in sys.stdin.readline()]; ii = 0

rows, cols, k = inp[ii:ii+3]; ii += 3
items = [[] for _ in range(rows+1)]
best = [0]*(cols+1)
for _ in range(k):
	inp[ii:ii+3]; ii += 3
	items[r].append([c, v])
for i in range(rows+1):
	items[i].sort()
ans = 0
for r in range(1, rows+1):
	dp = []
	best1, best2 = 0, 0
	Row = items[r]
	for c, v in Row:
		v1 = best[c] + v
		v2 = best1 + v
		v3 = best2 + v
		V = v1
		if V < v2:
			V = v2
		if V < v3:
			V = v3
		dp.append(V)
		if v1 > best1:
			best1 = v1
		if v2 > best2:
			best2 = v2
		if ans < V:
			ans = V
	for j in range(len(dp)):
		if best[Row[j][0]] < dp[j]:
			best[Row[j][0]] = dp[j]
	for j in range(2, cols+1):
		if best[j] < best[j-1]:
			best[j] = best[j-1]
print(ans)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
*p, = map(int, input().split())
p = [v - 1 for v in p]
*c, = map(int, input().split())
minc = float('-inf')

ans = minc


def get_loop(i):
    pos = i
    cnt = 0
    cur_score = 0
    while cnt == 0 or pos != i:
        pos = p[pos]
        cur_score = cur_score + c[pos]
        cnt += 1
    return cnt, cur_score

# print(get_loop(2))

def solve(pos, k):
    score = minc
    cur_score = 0
    loop_length, loop_score = get_loop(pos)
    if k >= 2 * loop_length and loop_score > 0:
        # print("%s: %s // %s, %s, %s" % (i, k, loop_length, cur_score, max_loop_score))
        cur_score = loop_score * ((k - loop_length) // loop_length)
        score = max(cur_score, score)
        k = k % loop_length + loop_length
    else:
        k = min(k, 2 * loop_length)
    for _ in range(k):
        pos = p[pos]
        cur_score += c[pos]
        score = max(cur_score, score)
    # print("%s: %s" % (i, score))
    return score

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

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.buffer.readline
R,C,K = map(int,input().split())
goods = [[-1]*(C+1) for _ in range(R+1)]
INF = 10**16
for i in range(K):
    ri,ci,vi = map(int,input().split())
    goods[ri][ci] = vi
DP = [[[-INF,-INF,-INF,-INF] for _ in range(C+1)] for _ in range(R+1)]
DP[1][1][0] = 0
if goods[1][1] != -1:
    DP[1][1][1] = goods[1][1]
for j in range(1,C):
    DP[1][j+1][0] = 0
    if goods[1][j+1] != -1:
        for k in range(1,3):
            DP[1][j+1][k] = max(DP[1][j][k],DP[1][j][k-1]+goods[1][j+1])
    else:
        for k in range(1,3):
        DP[1][j+1][k] = DP[1][j][k]
for i in range(1,R):
    DP[i+1][1][0] = max(DP[i][1])
    if goods[i+1][1] != -1:
        DP[i+1][1][1] = DP[i+1][1][0] + goods[i+1][1]
for i in range(2,R+1):
    for j in range(2,C+1):
        DP[i][j][0] = max(max(DP[i-1][j]),DP[i][j-1][0])
        if goods[i][j] != -1:
            DP[i][j][1] = max(DP[i][j][0]+goods[i][j],DP[i][j-1][1])
            DP[i][j][2] = max(DP[i][j-1][2],DP[i][j-1][1]+goods[i][j])
            DP[i][j][3] = max(DP[i][j-1][3],DP[i][j-1][2]+goods[i][j])
        else:
            for i in range(1,3):
            DP[i][j][k] = DP[i][j-1][k]
print(max(DP[R][C]))

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.buffer.readline
R,C,K = map(int,input().split())
goods = [[-1]*(C+1) for _ in range(R+1)]
INF = 10**16
for i in range(K):
    ri,ci,vi = map(int,input().split())
    goods[ri][ci] = vi
DP = [[[-INF,-INF,-INF,-INF] for _ in range(C+1)] for _ in range(R+1)]
DP[1][1][0] = 0
if goods[1][1] != -1:
    DP[1][1][1] = goods[1][1]
for j in range(1,C):
    DP[1][j+1][0] = 0
    if goods[1][j+1] != -1:
        for k in range(1,3):
        DP[1][j+1][k] = max(DP[1][j][k],DP[1][j][k-1]+goods[1][j+1])
    else:
        for k in range(1,3):
        DP[1][j+1][k] = DP[1][j][k]
for i in range(1,R):
    DP[i+1][1][0] = max(DP[i][1])
    if goods[i+1][1] != -1:
        DP[i+1][1][1] = DP[i+1][1][0] + goods[i+1][1]
for i in range(2,R+1):
    for j in range(2,C+1):
        DP[i][j][0] = max(max(DP[i-1][j]),DP[i][j-1][0])
        if goods[i][j] != -1:
            DP[i][j][1] = max(DP[i][j][0]+goods[i][j],DP[i][j-1][1])
            DP[i][j][2] = max(DP[i][j-1][2],DP[i][j-1][1]+goods[i][j])
            DP[i][j][3] = max(DP[i][j-1][3],DP[i][j-1][2]+goods[i][j])
        else:
            for i in range(1,3):
            DP[i][j][k] = DP[i][j-1][k]
print(max(DP[R][C]))