jiahuimbzuai/CoQuIR huggingface dataset:
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
 
#define rep(i, n) for (int i = (int)(0); i < (int)(n); ++i)
#define reps(i, n) for (int i = (int)(1); i <= (int)(n); ++i)
#define rrep(i, n) for (int i = ((int)(n)-1); i >= 0; i--)
#define rreps(i, n) for (int i = ((int)(n)); i > 0; i--)
#define irep(i, m, n) for (int i = (int)(m); i < (int)(n); ++i)
#define ireps(i, m, n) for (int i = (int)(m); i <= (int)(n); ++i)
#define FOR(e, c) for (auto &e : c)
#define SORT(v, n) sort(v, v + n);
#define vsort(v) sort(v.begin(), v.end());
#define rvisort(v) sort(v.begin(), v.end(), greater<int>());
#define all(v) v.begin(), v.end()
#define mp(n, m) make_pair(n, m);
#define cout(d) cout<<d<<endl;
#define coutd(d) cout<<std::setprecision(10)<<d<<endl;
#define cinline(n) getline(cin,n);
 
using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vll = vector<ll>;
using vvll = vector<vll>;
using pii = pair<int, int>;
using vpii = vector<pii>;
using vs = vector<string>;
using vd = vector<double>;
using ul = unsigned long;
 
template<class T, class C> void chmax(T& a, C b){ a>b?:a=b; }
template<class T, class C> void chmin(T& a, C b){ a<b?:a=b; }
 
const int mod=1e9+7;
 
struct mint {
  ll x;
  mint(ll x=0):x(x%mod){}
  mint& operator+=(const mint a) {
    if ((x += a.x) >= mod) x -= mod;
    return *this;
  }
  mint& operator-=(const mint a) {
    if ((x += mod-a.x) >= mod) x -= mod;
    return *this;
  }
  mint& operator*=(const mint a) {
    (x *= a.x) %= mod;
    return *this;
  }
  mint operator+(const mint a) const {
    mint res(*this);
    return res+=a;
  }
  mint operator-(const mint a) const {
    mint res(*this);
    return res-=a;
  }
  mint operator*(const mint a) const {
    mint res(*this);
    return res*=a;
  }
};
 
mint c[4005][4005];
void init() {
  c[0][0] = 1;
  for (int i = 0; i <= 4000; i++) {
    for (int j = 0; j <= i; j++) {
      c[i+1][j] += c[i][j];
      c[i+1][j+1] += c[i][j];
    }
  }
}
mint comb(int n, int k) {
  return c[n][k];
}
 
bool IsPrime(int num)
{
    if (num < 2) return false;
    else if (num == 2) return true;
    else if (num % 2 == 0) return false;
 
    double sqrtNum = sqrt(num);
    for (int i = 3; i <= sqrtNum; i += 2)
    {
        if (num % i == 0)
        {
            return false;
        }
    }
 
    return true;
}
 
map<ll, ll> primeFact(ll n) {
  map<ll, ll> res;
  for (ll i = 2; i * i <= n; i++) {
    while (n % i == 0) {
      res[i]++;
      n /= i;
    }
  }
  if (n != 1) res[n]++;
  return res;
}
 
void printv(vi& v){
  rep(i,v.size()) cout << v[i] << " ";
  cout << endl;
}
void printv(vll& v){
  rep(i,v.size()) cout << v[i] << " ";
  cout << endl;
}
int vtotal(vi& v){
  int total=0;
  rep(i,v.size()) total+=v[i];
  return total;
}
 
int main()
{
  //init(); // mint初期化
  cin.tie( 0 );
  ios::sync_with_stdio( false );
  int n,a;
  cin>>n>>a;
  string ans="No";
  if(n%500<=a)ans="Yes";
  cout(ans);
  return 0;
}
//  [c]
#include<stdio.h>
int main()
{
	int N,A,rem;
	scanf("%d%d",&N,&A);
	rem=N%500;
	if(rem>A)
		printf("No\n");
	else
		printf("Yes\n");
	return 0;
}
//  [c]
#include<stdio.h>


int main()
{

    int a,b,c;

    scanf("%d%d",&a,&b);

    c=a%500;

    if(b>=c) printf("Yes\n");
    else printf("No\n");


    return 0;

}
//  [c]
#include <stdio.h>

int main()
{
    int N,A,x;
    scanf("%d %d",&N,&A);
    x=(N%500);
    if(x==0)
    {
        printf("Yes");
    }
    else if(x<=A)
    {
        printf("Yes");
    }
    else
    {
        printf("No");
    }

    return 0;
}
//  [javascript]
'use strict'

function main(s) {

  s = s.split('\n');
  const n = Number(s[0]);
  const a = Number(s[1]);

  const ans = (a >= (n % 500)) ? 'Yes' : 'No';
  console.log(ans);
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input){
  var inp = input.split('\n');
  var N = parseInt(inp[0].trim());
  var A = parseInt(inp[1].trim());
  
  if(N % 500 <= A ){
    console.log('Yes');
  } else {
    console.log('No');
  }
  
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
'use strict'

function main(input) {
  input = input
    .trim()
    .split('\n')
    .map(Number)
  const n = input[0] % 500
  const ans = n <= input[1] ? 'Yes' : 'No'
  console.log(ans)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [go]
///
// File:  a.go
// Author: ymiyamoto
//
// Created on Sun Feb 18 21:00:18 2018
//
package main

import (
	"fmt"
)

func main() {
	var N, A int
	fmt.Scan(&N, &A)
	if N%500 <= A {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}
//  [ruby]
require 'prime'
require 'set'
require 'tsort'
include Math
ALP = ('a'..'z').to_a
INF = 0xffffffffffffffff
def max(a,b);              a > b ? a : b                              end
def min(a,b);              a < b ?  a : b                             end
def swap(a,b);             a, b = b, a                                end
def gif;                   gets.to_i                                  end
def gff;                   gets.to_f                                  end
def gsf;                   gets.chomp                                 end
def gi;                    gets.split.map(&:to_i)                     end
def gf;                    gets.split.map(&:to_f)                     end
def gs;                    gets.chomp.split.map(&:to_s)               end
def gc;                    gets.chomp.split('')                       end
def pr(num);               num.prime_division                         end
def pr?(num);              Prime.prime?(num)                          end
def digit(num);            num.to_s.length                            end
def array(s,ini=nil);      Array.new(s){ini}                          end
def darray(s1,s2,ini=nil); Array.new(s1){Array.new(s2){ini}}          end
def rep(num);              num.times{|i|yield(i)}                     end
def repl(st,en,n=1);       st.step(en,n){|i|yield(i)}                 end

n = gif
a = gif
puts n % 500 <= a ? 'Yes' : 'No'
//  [ruby]
a,b=`dd`.split.map(&:to_i)
puts a%500<=b ? "Yes":"No"
//  [ruby]
#!/usr/bin/env ruby

require 'set'

class Hash
  def push(key, value)
    self[key] = [] if self[key] == nil
    self[key].push(value)
  end
end

class Array
  def lower_bound(value)
    left = -1;
    right = self.length;
    while left + 1 < right
      mid = left + (right - left) / 2;
      if self[mid] >= value
        right = mid
      else
        left = mid
      end
    end
    right
  end

  def unique
    res = [self.first]
    each_cons(2) do |a, b|
      if a != b
        res.push(b)
      end
    end
    res
  end
end

def get_ints
  gets.chomp.split.map(&:to_i)
end

def get_ints_minus_one
  get_ints.map { |x| x - 1 }
end

def get_int
  gets.chomp.to_i
end

N = get_int
A = get_int

if A >= N % 500
  puts 'Yes'
else
  puts 'No'
end
//  [rust]
use proconio::{input, fastout};
use proconio::marker::{Chars};
use proconio::marker::Usize1;
use std::cmp::*;

macro_rules! debug {
      ($($a:expr),*) => {
          eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

#[fastout]
fn main() {
    input!{
        n: usize,
        a: usize,
    }

    if n%500<=a {
        println!("Yes");
    } else {
        println!("No");
    }

}
//  [rust]
use proconio::input;
use proconio::marker::Chars;
fn main() {
    input!{
        n:usize,a:usize
    };
    println!("{}",if (n % 500) <= a {"Yes"} else {"No"});
}
//  [rust]
#[allow(unused_imports)]
use proconio::marker::{Bytes, Chars, Usize1};
use proconio::{fastout, input};
#[fastout]
fn main() {
    input! {
        n: usize,
        a: usize,
    }
    let amari = n % 500;
    if amari <= a {
        println!("Yes");
    } else {
        println!("No");
    }
}
//  [typescript]
import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const main = (input: string[][]) => {
  const N = Number(input[0][0]);
  const A = Number(input[1][0]);

  return N % 500 <= A ? "Yes" : "No";
};

console.log(main(read()));
//  [typescript]
const input=require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/);const nin=()=>{const r = input[0];input.shift();return Number(r)};const nrin=(n)=>{const a:number[]=[];rep(n,()=>a.push(nin()));return a};const sin=()=>{const r = input[0];input.shift();return String(r)};const out=(...a)=>{console.log(...a)};const floor=(a)=>{return Math.floor(a)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const rep=(n, callback)=>{for(let i = 0;i < n; i++){callback()}};const strrep=(s, i, v)=>{return s.slice(0, i)+v+s.slice(i+1);};const permutation=({result=[],pre=[],post,n=post.length})=>{if(n>0){post.forEach((_,i)=>{const rest=[...post];const elem=rest.splice(i, 1);permutation({result, pre: [...pre,...elem],post:rest,n:n-1})})}else{result.push(pre)}return result};const sw=(s,a:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<a.length;i+=2){if(op==='=='){if(s==a[i])return a[i+1]}else if(op==='>='){if(s>=a[i])return a[i+1]}else if(op==='<='){if(s<=a[i])return a[i+1]}else if(op==='>'){if(s>a[i])return a[i+1]}else if(op==='<'){if(s<a[i])return a[i+1]}}return a[a.length-1];};const or=(a,...b)=>{for(let i=0;i<b.length;i++)if(a==b[i])return true;return false};const maxindex=(...a)=>{return a.indexOf(Math.max.apply(null,a))};const asc=(ar:number[])=>{return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{return ar.sort((a,b)=>{return b-a})};const ceil=a=>{return Math.ceil(a)};const srin=s=>{const a:string[]=[];rep(s,()=>a.push(sin()));return a};let ssinteger=-1;const ssin=()=>{ssinteger++;return input[0][ssinteger]};
const main = ()=>{
  let[a,b]=nrin(2)
  out(floor(a/500)*500+b>=a?'Yes':'No')
}
main()
//  [python]
import sys

inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
shift = int(10**9 + 1)
rows, cols, k = inp[ii:ii+3]; ii += 3
items = [[] for _ in range(rows+1)]
best = [0]*(cols+1)
for _ in range(k):
	r, c, v = inp[ii:ii+3]; ii += 3
	items[r].append(c*shift+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 X in Row:
		c, v = X//shift, X%shift
		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)):
		c = Row[j]//shift
		if best[c] < dp[j]:
			best[c] = dp[j]
	for j in range(2, cols+1):
		if best[j] < best[j-1]:
			best[j] = best[j-1]
print(ans)
//  [python]
import sys
from collections import deque
import bisect
import copy
import heapq
import itertools
import math
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


def main():
    R, C, K = read_values()
    V = [0] * (R * C)
    for _ in range(K):
        r, c, v = read_values()
        r -= 1
        c -= 1
        V[r * C + c] = v
    
    dp = [0 for _ in range(R * C * 4)]
    for i in range(R * C):
        r = i // C
        c = i % C
        if c + 1 < C:
            # not take
            for k in range(4):
                dp[4 * (i + 1) + k] = max(dp[4 * (i + 1) + k], dp[4 * i + k])

            # take 
            for k in range(3):
                dp[4 * (i + 1) + k + 1] = max(dp[4 * (i + 1) + k + 1], dp[4 * i + k] + V[i])

        # next r
        if r + 1 < R:
            for k in range(4):
                dp[4 * (i + C)] = max(dp[4 * (i + C)], dp[4 * i + k] + (V[i] if k < 3 else 0))

    res = 0
    for k in range(4):
        res = max(res, dp[4 * (R * C - 1) + k] + (V[-1] if k < 3 else 0))

    print(res)


if __name__ == "__main__":
    main()
//  [python]
def resolve():
    r, c, k = map(int, input().split())
    dict = {}
    for i in range(k):
        a,b,z = map(int, input().split())
        a -= 1
        b -= 1
        dict[(a,b)] = z
    now = [[0]*4 for _ in range(c)]
    prev = [0]*c

    if (0,0) in dict:
        now[0][1] = dict[(0,0)]
    for i in range(1, c):
        if (0, i) in dict:
            now[i][0] = now[i-1][0]
            now[i][1] = max(dict[(0,i)]+now[i-1][0] , now[i-1][1])
            if now[i-1][1] != 0:
                now[i][2] = max(dict[(0,i)]+now[i-1][1], now[i-1][2])
            if now[i - 1][2] != 0:
                now[i][3] = max(dict[(0,i)]+now[i-1][2], now[i-1][3])
        else:
            now[i][0] = now[i-1][0]
            now[i][1] = now[i-1][1]
            now[i][2] = now[i-1][2]
            now[i][3] = now[i-1][3]
    for i in range(c):
        prev[i] = max(now[i])
    for i in range(1, r):
        now = [[0] * 4 for _ in range(c)]
        now[0][0] = prev[0]
        if (i, 0) in dict:
            now[0][1] = dict[(i,0)]+now[0][0]

        for j in range(1, c):
            now[j][0] = max(now[j-1][0], prev[j])

            if (i,j) in dict:
                if now[j-1][2] != 0:
                    a3 = now[j-1][2]+dict[(i,j)]
                else:
                    a3 = 0
                if now[j][2] != 0:
                    a4 = now[j][2]+dict[(i,j)]
                else:
                    a4 = 0

                if now[j-1][1] != 0:
                    a1 = now[j-1][1]+dict[(i,j)]
                else:
                    a1 = 0
                if now[j][1] != 0:
                    a2 = now[j][1]+dict[(i,j)]
                else:
                    a2 = 0
                now[j][3] = max(now[j - 1][3], a3, a4)
                now[j][2] = max(now[j-1][2], a1, a2)
                now[j][1] = max(now[j-1][1], now[j-1][0] + dict[(i,j)],now[j][0] + dict[(i,j)])
            else:
                now[j][1] = now[j-1][1]
                now[j][2] = now[j-1][2]
                now[j][3] = now[j-1][3]
        prev = [0]*c

        for j in range(c):
            prev[j] = max(now[j])
    print(prev[-1])
resolve()
//  [python]
R,C,K=map(int,input().split())

V=[[0 for _ in range(C)] for _ in range(R)]

for i in range(K):
    r,c,v=map(int,input().split())
    V[r-1][c-1]=v

dp=[[0 for _ in range(4)] for _ in range(C+1)]
for i in range(R):
    ndp=[[0 for _ in range(4)] for _ in range(C+1)]
    for j in range(C):
        ndp[j][0]=max(dp[j])

    for j in range(C):
        v=V[i][j]
        for n in range(1,4):
            ndp[j][n]=max(ndp[j-1][n-1]+v,dp[j][3]+v,ndp[j-1][n])

    dp=ndp

print(max(dp[C-1]))
//  [java]
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		var sc = new Scanner(System.in);
		var r = sc.nextInt();
		var c = sc.nextInt();
		var k = sc.nextInt();
		var v = new long[r][c][5];
		for (var i = 0; i < k; i++) {
			v[sc.nextInt() - 1][sc.nextInt() - 1][0] = sc.nextInt();
		}
		sc.close();

		for (var i = 0; i < r; i++) {
			for (var j = 0; j < c; j++) {
				var cv = v[i][j][0];
				v[i][j][0] = 0;
				for (var ic = 0; ic < 4; ic++) {
					var rv1 = (i > 0 ? getValue(v, i - 1, j) : 0);
					var rv2 = (j > 0 ? v[i][j - 1][ic] : 0);
					var rv3 = (j > 0 ? v[i][j - 1][ic + 1] : 0);
					if (cv > 0) {
						if (ic == 0) {
							v[i][j][ic + 1] = Math.max(Math.max(rv1 + cv, rv2 + cv), rv3);
						} else if (rv2 > 0) {
							v[i][j][ic + 1] = Math.max(rv2 + cv, rv3);
						}
					} else {
						if (ic == 0) {
							v[i][j][ic] = Math.max(rv1, rv2);
						} else {
							v[i][j][ic] = rv2;
						}
					}
				}
				//System.out.printf("%d %d %d %d\r\n", v[i][j][0], v[i][j][1], v[i][j][2], v[i][j][3]);
			}
			//System.out.println("----------");
		}

		System.out.println(getValue(v, r - 1, c - 1));
	}

	private static long getValue(long[][][] v, int i, int j) {
		return Math.max(Math.max(Math.max(v[i][j][0], v[i][j][1]), v[i][j][2]), v[i][j][3]);
	}
}
//  [cpp]
#pragma GCC optimize ("O2")
#pragma GCC target ("avx2")
//#include<bits/stdc++.h>
#include<algorithm>
#include<cstdio>

using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int bm = 3010;
ll BIT[bm];
void add(int A, ll B) {
	while (A <= bm) {
		BIT[A] = max(BIT[A], B);
		A += A & -A;
	}
}
ll query(int A) {
	ll kotae = 0;
	while (A > 0) {
		kotae = max(BIT[A], kotae);
		A -= A & -A;
	}
	return kotae;
}

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread_unlocked(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

ll V[200000], tmp[200000];

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int R = getint(), C = getint(), K = getint();

	rep(i, K) {
		ll r = getint(), c = getint(), v = getint();
		V[i] = v << 30 | r << 12 | c;
	}

	const int b = 12;
	int kazu[1 << b] = {}, kazu2[1 << b] = {};
	rep(i, K) kazu[V[i] & ((1 << b) - 1)]++;
	rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
	for (int i = K - 1; i >= 0; i--) tmp[--kazu[V[i] & ((1 << b) - 1)]] = V[i];
	rep(i, K) kazu2[tmp[i] >> b & ((1 << b) - 1)]++;
	rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
	for (int i = K - 1; i >= 0; i--) V[--kazu2[tmp[i] >> b & ((1 << b) - 1)]] = tmp[i];

	int mae = -1;
	ll A[4] = {};
	ll L[3001];
	int l = 0;
	rep(k, K) {
		int v = V[k] >> 30;
		int i = V[k] >> 12 & 4095;
		int j = V[k] & 4095;
		if (mae != i) {
			mae = i;
			A[0] = 0;
			A[1] = 0;
			A[2] = 0;
			A[3] = 0;
			rep(a, l) add(L[a] & 4095, L[a] >> 12);
			l = 0;
		}
		ll kari = query(j);
		A[0] = kari;
		chmax(A[3], kari);
		chmax(A[2], kari);
		chmax(A[1], kari);
		chmax(A[3], A[2] + v);
		chmax(A[2], A[1] + v);
		chmax(A[1], A[0] + v);
		L[l++] = A[3] << 12 | j;
	}

	rep(a, l) add(L[a] & 4095, L[a] >> 12);
	ll kotae = query(C);

	printf("%lld\n", kotae);

	Would you please return 0;
}
//  [cpp]
#include <iostream> 
#include <vector>
#include <cmath>
#include <string>
#include <sstream>
#include <algorithm>
#include <queue>
#include <stack>
#include <unordered_set>
#include <set>
#include <unordered_map>
#include <map>
#include <iomanip>
#include <cctype>
#include <climits>

using namespace std;

using ll = long long int;
using ii = pair<int, int>;
using vi = vector<ll>;
using vii = vector<ii>;
using vvi = vector<vi>;
using vvvi = vector<vvi>;



#define mp(a,b) make_pair(a,b)

const int MOD = 1000 * 1000 * 1000 + 7;

ll dp(int x, int y, int it, vvi const& mat, vvvi & marcaje) {
	if (y >= mat.size()) return 0;
	else if (x >= mat[0].size()) return 0;
	else if (marcaje[y][x][it] != -1) return marcaje[y][x][it];
	else {
		//No hay item, vamos para la derecha o para abajo
		if (mat[y][x] == 0) {
			ll s1 = dp(x + 1, y, it, mat, marcaje);
			ll s2 = dp(x, y + 1, 0, mat, marcaje);
			marcaje[y][x][it] = max(s1, s2);
			return marcaje[y][x][it];
		}
		else {
			//Podemos o coger el ítem o no cogerlo

			//Cogemos el item
			//Vamos hacia la derecha si podemos
			ll s1 = 0;
			if(it < 2) s1 = dp(x + 1, y, it + 1, mat, marcaje) + mat[y][x];

			//Vamos hacia abajo
			ll s2 = dp(x, y + 1, 0, mat, marcaje) + mat[y][x];

			//No lo cogemos
			ll s3 = dp(x + 1, y, it, mat, marcaje);
			ll s4 = dp(x, y + 1, 0, mat, marcaje);

			marcaje[y][x][it] = max({ s1, s2,s3, s4 });
			return marcaje[y][x][it];
		}
	}
}

int main() {
	cin.tie(NULL);
	ios_base::sync_with_stdio(false);
	int r, c, k;
	cin >> r >> c >> k;

	vvi mat(r, vi(c));

	for (int i = 0; i < k; ++i) {
		int fil, col, val;
		cin >> fil >> col >> val;
		mat[fil - 1][col - 1] = val;
	}

	vvvi marcaje(r, vvi(c, vi(4, -1)));
	cout << dp(0, 0, 0, mat, marcaje) << '\n';
	return 0;
}
//  [cpp]
//@formatter:off
#include<bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < int(n); ++i)
#define rrep(i,n) for (int i = int(n)-1; i >= 0; i--)
#define rep2(i,s,n) for (int i = int(s); i < int(n); ++i)
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define pb push_back
#define eb emplace_back
#define vi vector<int>
#define vvi vector<vector<int>>
#define vl vector<ll>
#define vvl vector<vector<ll>>
#define vd vector<double>
#define vvd vector<vector<double>>
#define vs vector<string>
#define vc vector<char>
#define vvc vector<vector<char>>
#define vb vector<bool>
#define vvb vector<vector<bool>>
#define vp vector<P>
#define vvp vector<vector<P>>
using namespace std;
using ll = long long;
using P = pair<int,int>;
using LP = pair<ll,ll>;
template<class S,class T> istream& operator>>(istream &is,pair<S,T> &p) { return is >> p.first >> p.second; }
template<class S,class T> ostream& operator<<(ostream &os,const pair<S,T> &p) { return os<<'{'<<p.first<<","<<p.second<<'}'; }
template<class T> istream& operator>>(istream &is,vector<T> &v) { for(T &t:v){is>>t;} return is; }
template<class T> ostream& operator<<(ostream &os,const vector<T> &v) { os<<'[';rep(i,v.size())os<<v[i]<<(i==int(v.size()-1)?']':','); return os; }
void Yes(bool b) { cout << (b ? "Yes" : "No") << '\n'; }
void YES(bool b) { cout << (b ? "YES" : "NO") << '\n'; }
template<class T> bool chmin(T& a,T b) {if(a > b){a = b; return true;} return false;}
template<class T> bool chmax(T& a,T b) {if(a < b){a = b; return true;} return false;}
const int inf = 1001001001;
const ll linf = 1001001001001001001;
//@formatter:on

ll dp[3010][3010];

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int R, C, k;
    cin >> R >> C >> k;
    vvp item(R);
    rep(_, k) {
        int r, c, v;
        cin >> r >> c >> v;
        r--;
        item[r].eb(c, v);
    }
    rep(i, R) sort(all(item[i]));
    rep(i, R) rep(j, C + 1) {
            chmax(dp[i + 1][j], dp[i][j]);
            auto it = lower_bound(all(item[i]), j,
                                  [](P &p,int val){ return p.first < val; });
            vi ls;
            while (it != item[i].end()) {
                ls.pb(it->second);
                if (ls.size() > 3) {
                    ls.erase(min_element(all(ls)));
                }
                ll sum = accumulate(all(ls), 0LL);
                chmax(dp[i + 1][it->first], dp[i][j] + sum);
                it++;
            }
        }
    ll ans = 0;
    rep(i, 3010) rep(j, 3010) chmax(ans, dp[i][j]);
    cout << ans << endl;
}
//  [c]
#include<stdio.h>
int main()
{
	int R, C, K;
	scanf("%d %d %d", &R, &C, &K);
	int i, j;
	int r[200005], c[200005];
	long long int v[200005];
	for (i = 0; i < K; i++)
		scanf("%d %d %lld", &r[i], &c[i], &v[i]);
	int ind[3003][3003];
	for (i = 0; i < R; i++)
		for (j = 0; j < C; j++)
			ind[i][j] = -1;
	for (i = 0; i < K; i++)
		ind[r[i] - 1][c[i] - 1] = i;
	long long int dp[2][4][3003];
	for (i = 0; i < 4; i++)
		for (j = 0; j < C; j++)
			dp[0][i][j] = dp[1][i][j] = 0;
	for (i = 0; i < R; i++)
	{
		for (j = 0; j < C; j++)
		{
			dp[1][0][j] = dp[0][0][j];
			if (dp[1][0][j] < dp[0][1][j])
				dp[1][0][j] = dp[0][1][j];
			if (dp[1][0][j] < dp[0][2][j])
				dp[1][0][j] = dp[0][2][j];
			if (dp[1][0][j] < dp[0][3][j])
				dp[1][0][j] = dp[0][3][j];
			dp[1][1][j] = 0;
			dp[1][2][j] = 0;
			if (j > 0)
			{
				if (dp[1][0][j] < dp[1][0][j - 1])
					dp[1][0][j] = dp[1][0][j - 1];
				if (dp[1][1][j] < dp[1][1][j - 1])
					dp[1][1][j] = dp[1][1][j - 1];
				if (dp[1][2][j] < dp[1][2][j - 1])
					dp[1][2][j] = dp[1][2][j - 1];
				if (dp[1][3][j] < dp[1][3][j - 1])
					dp[1][3][j] = dp[1][3][j - 1];
			}
			if (ind[i][j] >= 0)
			{
				if (dp[1][3][j] < dp[1][2][j] + v[ind[i][j]])
					dp[1][3][j] = dp[1][2][j] + v[ind[i][j]];
				if (dp[1][2][j] < dp[1][1][j] + v[ind[i][j]])
					dp[1][2][j] = dp[1][1][j] + v[ind[i][j]];
				if (dp[1][1][j] < dp[1][0][j] + v[ind[i][j]])
					dp[1][1][j] = dp[1][0][j] + v[ind[i][j]];
			}
		}
		for (j = 0; j < C; j++)
		{
			dp[0][0][j] = dp[1][0][j];
			dp[0][1][j] = dp[1][1][j];
			dp[0][2][j] = dp[1][2][j];
			dp[0][3][j] = dp[1][3][j];
		}
	}
	long long int ans = dp[0][0][C - 1];
	if (ans < dp[0][1][C - 1])
		ans = dp[0][1][C - 1];
	if (ans < dp[0][2][C - 1])
		ans = dp[0][2][C - 1];
	if (ans < dp[0][3][C - 1])
		ans = dp[0][3][C - 1];
	printf("%lld\n", ans);
	return 0;
}
//  [c]
#include <stdio.h>

int main()
{
	int i, R, C, K, r, c, v, item[3001][3001] = {};
	scanf("%d %d %d", &R, &C, &K);
	for (i = 1; i <= K; i++) {
		scanf("%d %d %d", &r, &c, &v);
		item[r][c] = v;
	}
	
	int j, k;
	long long dp[4][3001] = {};
	for (i = 1; i <= R; i++) {
		for (j = 1; j <= C; j++) {
			for (k = 1; k <= 3; k++) {
				if (dp[k][j] > dp[0][j-1]) dp[0][j-1] = dp[k][j];
				dp[k][j] = 0;
			}
			for (k = 0; k <= 3; k++) if (dp[k][j-1] > dp[k][j]) dp[k][j] = dp[k][j-1];
			for (k = 1; k <= 3; k++) if (dp[k-1][j-1] + item[i][j] > dp[k][j]) dp[k][j] = dp[k-1][j-1] + item[i][j];
		}
	}

	for (k = 1; k <= 3; k++) if (dp[k][C] > dp[0][C]) dp[0][C] = dp[k][C];
	printf("%lld\n", dp[0][C]);
	fflush(stdout);
	return 0;
}
//  [c]
#include <float.h>
#include <inttypes.h>
#include <limits.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <math.h>
#ifdef __cplusplus
#include <bits/stdc++.h>
#endif
#pragma GCC target("avx2")
//#pragma GCC optimize("O3")
//#pragma GCC optimize("unroll-loops")

#define getchar getchar_unlocked
#define putchar putchar_unlocked
int32_t nextint(void){ char c=getchar(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar(); bool s=false; if(c=='-'){s=true;c=getchar();} uint32_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return s?-x:x; }
int64_t nextlong(void){ char c=getchar(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar(); int s=0; if(c=='-'){s=1;c=getchar();} uint64_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return s?-x:x; }
uint32_t nextstr(char *s){ char c=getchar(); while(c==' '||c=='\n') c=getchar(); uint32_t len=0; while(c!=' '&&c!='\n'){ *s++=c; len++; c=getchar(); } *s='\0'; return len; }
void rsorta_d32(void *base, const int count, const int size, const int index){
	typedef int32_t rsort_t;
	rsort_t (*a)[size] = (rsort_t(*)[size])base;
	rsort_t (*b)[size] = (rsort_t(*)[size])malloc(count*size*sizeof(rsort_t));
	int c[0x100];
	for(int k=0; k<4; k++){
		memset(c, 0, sizeof(c)); for(int i=0; i<count; i++){ c[(a[i][index]>>(k<<3))&0xFF]++; } for(int i=1; i<0x100; i++) c[i]+=c[i-1]; for(int i=count-1; i>=0; i--){ int to=--c[(a[i][index]>>(k<<3))&0xFF]; for(int j=0; j<size; j++){ b[to][j]=a[i][j]; } }{rsort_t(*t)[size]=a; a=b; b=t;}
	}
	free(b);
}

int m[3001][3001];
long d[3001][3001][4];
int main(void){
	int w=nextint();
	int h=nextint();
	int k=nextint();
	for(int i=0; i<k; i++){
		int x=nextint();
		int y=nextint();
		int v=nextint();
		m[x][y]=v;
	}
	for(int x=1; x<=w; x++){
		for(int y=1; y<=h; y++){
			d[x][y][0]=d[x][y-1][0];
			if(d[x][y][0]<d[x-1][y][0]) d[x][y][0]=d[x-1][y][0];
			if(d[x][y][0]<d[x-1][y][1]) d[x][y][0]=d[x-1][y][1];
			if(d[x][y][0]<d[x-1][y][2]) d[x][y][0]=d[x-1][y][2];
			if(d[x][y][0]<d[x-1][y][3]) d[x][y][0]=d[x-1][y][3];
			d[x][y][1]=d[x][y-1][1];
			d[x][y][2]=d[x][y-1][2];
			d[x][y][3]=d[x][y-1][3];
			if(m[x][y]>0){
				if(d[x][y][1]<d[x-1][y][0]+m[x][y]) d[x][y][1]=d[x-1][y][0]+m[x][y];
				if(d[x][y][1]<d[x-1][y][1]+m[x][y]) d[x][y][1]=d[x-1][y][1]+m[x][y];
				if(d[x][y][1]<d[x-1][y][2]+m[x][y]) d[x][y][1]=d[x-1][y][2]+m[x][y];
				if(d[x][y][1]<d[x-1][y][3]+m[x][y]) d[x][y][1]=d[x-1][y][3]+m[x][y];
				if(d[x][y][1]<d[x][y-1][0]+m[x][y]) d[x][y][1]=d[x][y-1][0]+m[x][y];
				if(d[x][y][2]<d[x][y-1][1]+m[x][y]) d[x][y][2]=d[x][y-1][1]+m[x][y];
				if(d[x][y][3]<d[x][y-1][2]+m[x][y]) d[x][y][3]=d[x][y-1][2]+m[x][y];
			}
			//printf("%d %d %ld %ld %ld %ld\n", x, y, d[x][y][0], d[x][y][1], d[x][y][2], d[x][y][3]);
		}
	}
	long ans=d[w][h][0];
	if(ans<d[w][h][1]) ans=d[w][h][1];
	if(ans<d[w][h][2]) ans=d[w][h][2];
	if(ans<d[w][h][3]) ans=d[w][h][3];
	printf("%ld\n", ans);
}
//  [c]
long V[3030][3030],dp[3030][3030][5];
main(R,C,K){
	scanf("%d%d%d",&R,&C,&K);
	for(int i=0;i<K;i++)
	{
		int r,c,v;
		scanf("%d%d%d",&r,&c,&v);
		V[r][c]=v;
	}
	for(int i=0;i<=R;i++)for(int j=0;j<=C;j++)for(int k=0;k<4;k++)
	{
		for(int r=0;r<2;r++)
		{
			int v=V[i+1-r][j+r];
			for(int l=0;l<2;l++)
			{
				int nk=r*k+l;
				if(dp[i+1-r][j+r][nk]<dp[i][j][k]+l*v)dp[i+1-r][j+r][nk]=dp[i][j][k]+l*v;
			}
		}
		if(dp[i][j][k+1]<dp[i][j][k])dp[i][j][k+1]=dp[i][j][k];
	}
	printf("%ld\n",dp[R][C][3]);
}
//  [c]
#include<stdio.h>
long long MAX(long long a,long long b){return a<b?b:a;}
long long d[3010][3010][5]={},m[3010][3010];
int main(){
  int h,w,i,j,k,n,y,x,a;
  scanf("%d %d %d",&h,&w,&n);
  for(i=0;i<n;i++){
    scanf("%d %d %d",&y,&x,&a);
    m[y][x]=a;
  }
  for(i=1;i<=h;i++){
    for(j=1;j<=w;j++){
      for(k=0;k<=3;k++){/*
	d[i+1][j][k+1]=MAX(d[i+1][j][k+1],d[i][j][k]+m[i][j]);
	d[i+1][j][k  ]=MAX(d[i+1][j][k  ],d[i][j][k]        );
	if(k<2)d[i][j+1][0  ]=MAX(d[i][j+1][0  ],d[i][j][k]+m[i][j]);
	d[i][j+1][0  ]=MAX(d[i][j+1][0],d[i][j][k]);/*/
	d[i][j+1][k+1]=MAX(d[i][j+1][k+1],d[i][j][k]+m[i][j]);
	d[i][j+1][k  ]=MAX(d[i][j+1][k  ],d[i][j][k]        );
	if(k<3)d[i+1][j][0  ]=MAX(d[i+1][j][0],d[i][j][k]+m[i][j]);
	       d[i+1][j][0  ]=MAX(d[i+1][j][0],d[i][j][k]);//*/
      }
    }
  }
  for(i=0;i<4;i++)d[h][w+1][0]=MAX(d[h][w+1][0],d[h][w+1][i]);
  printf("%lld\n",d[h][w+1][0]);
  return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int64_t R,C,K;
int64_t item[3010][3010];
int64_t dp[3010][3010][5];

void chmax(int r, int c, int g, int64_t val)
{
    if (dp[r][c][g] < val) {
        dp[r][c][g] = val;
    }
}

int main()
{
    int i,r,c,g;
    int _;
    int64_t curval,ans;
    i=r=c=g=curval=0;
    _=scanf("%ld%ld%ld", &R,&C,&K);
    for (i=0; i<K; i++) {
        _=scanf("%d%d%ld", &r,&c,&curval);
        item[r][c] = curval;
    }
    i=r=c=g=curval=0;
    dp[1][1][0] = 0;
    if (item[1][1] > 0) {
        dp[1][1][1] = item[1][1];
    }
    for (r=1;r<=R;r++) {
        for (c=1;c<=C;c++) {
            for (g=0;g<=3;g++) {
                curval = dp[r][c][g];
                if (c < C) {
                    /* right */
                    if ((item[r][c+1]) && (g < 3)) {
                        chmax(r,c+1,g+1,curval+item[r][c+1]);
                    }
                    chmax(r,c+1,g,curval);
                }
                if (r < R) {
                    /* down */
                    if (item[r+1][c]) {
                        chmax(r+1,c,1,curval+item[r+1][c]);
                    }
                    chmax(r+1,c,0,curval);
                }
            }
        }
    }
    ans = dp[R][C][0];
    if (dp[R][C][1] > ans) ans = dp[R][C][1];
    if (dp[R][C][2] > ans) ans = dp[R][C][2];
    if (dp[R][C][3] > ans) ans = dp[R][C][3];
    printf("%ld\n",ans);
    return 0;
}
//  [javascript]
function Main(input) {
  input = input.trim().split("\n");
  const [R, C, n] = input.shift().split(" ").map((a) => parseInt(a, 10));
  const values = input.map((a) => a.split(" ").map((b) => parseInt(b, 10)));

  let i, j, k;
  a = [];
  dp = [];

  for (let i=0; i<n; i++) {
    const [r, c, v] = values[i];
    a[r - 1] = a[r - 1] || [];
    a[r - 1][c - 1] = v;
  }

  for (i=0; i<R; i++) {
    dp[i] = dp[i] || [];
    dp[i+1] = dp[i+1] || [];
    for (j=0; j<C; j++) {
      dp[i][j] = dp[i][j] || [0, 0, 0, 0];
      dp[i][j+1] = dp[i][j+1] || [0, 0, 0, 0];
      dp[i+1][j] = dp[i][j] || [0, 0, 0, 0];
      for (k = 2; k >= 0; k--) {
        dp[i][j][k+1] = Math.max(dp[i][j][k+1], dp[i][j][k]  + (a[i] && a[i][j] || 0));
      }
      for (k = 0; k<4; k++) {
        dp[i+1][j][0] = Math.max(dp[i+1][j][0], dp[i][j][k]);
        dp[i][j+1][k] = Math.max(dp[i][j+1][k], dp[i][j][k]);
      }
    }
  }

  let ans = 0;
  for (k = 0; k<4; k++) {
    ans = Math.max(ans, dp[R-1][C-1][k]);
  }
  console.log(ans);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}

var myOut = main();
if(myOut !== undefined)console.log(String(myOut));

function main(){
  var [r,c,k] = nexts(3);
  var a = xArray("new Map()",r+1);
  for(var i = 0; i < k; i++){
    var [u,v,w] = nexts(3);
    a[u].set(v,w);
  }
  var dp = xArray(0,c+1,4);
  for(var y = 1; y <= r; y++){
    var dp2 = xArray(0,c+1,4), b;
    for(var x = 1; x <= c; x++){
      dp2[x][0] = Math.max(dp[x][3], dp2[x-1][0]);
      if(b=a[y].get(x))for(var i = 1; i <= 3; i++){
        dp2[x][i] = Math.max(dp[x][3]+b, dp2[x-1][i-1]+b, dp2[x-1][i]);
      }else for(var i = 1; i <= 3; i++){
        dp2[x][i] = Math.max(dp[x][3], dp2[x-1][i]);
      }
    }
    dp = dp2;
  }
  return dp[c][3];
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func main() {
	defer flush()

	R := readInt()
	C := readInt()
	K := readInt()

	goods := make([][]int, R)
	for i := 0; i < R; i++ {
		goods[i] = make([]int, C)
	}
	for i := 0; i < K; i++ {
		r := readInt() - 1
		c := readInt() - 1
		v := readInt()
		goods[r][c] = v
	}

	dp := make([]int, C+1)
	cur := make([]int, 4)
	for i := 0; i < R; i++ {
		for k := 0; k < 4; k++ {
			cur[k] = 0
		}
		cur[0] = dp[0]
		for j := 0; j < C; j++ {
			if goods[i][j] != 0 {
				for k := 2; k >= 0; k-- {
					cur[k+1] = max(cur[k+1], cur[k]+goods[i][j])
				}
			}
			for k := 0; k < 4; k++ {
				dp[j] = max(dp[j], cur[k])
			}
			cur[0] = max(cur[0], dp[j+1])
		}
	}

	result := -1
	for k := 0; k < 4; k++ {
		result = max(result, cur[k])
	}

	println(result)
}

const (
	ioBufferSize = 1 * 1024 * 1024 // 1 MB
)

var stdinScanner = func() *bufio.Scanner {
	result := bufio.NewScanner(os.Stdin)
	result.Buffer(make([]byte, ioBufferSize), ioBufferSize)
	result.Split(bufio.ScanWords)
	return result
}()

func readString() string {
	stdinScanner.Scan()
	return stdinScanner.Text()
}

func readInt() int {
	result, err := strconv.Atoi(readString())
	if err != nil {
		panic(err)
	}
	return result
}

var stdoutWriter = bufio.NewWriter(os.Stdout)

func flush() {
	stdoutWriter.Flush()
}

func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(stdoutWriter, args...)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

var (
	goods [3000][3000]int
)

func main() {
	defer flush()

	R := readInt()
	C := readInt()
	K := readInt()
	for i := 0; i < K; i++ {
		r := readInt() - 1
		c := readInt() - 1
		v := readInt()
		goods[r][c] = v
	}

	n := make([]int, C+1)
	c := make([]int, 4)
	for i := 0; i < R; i++ {
		for k := 0; k < 4; k++ {
			c[k] = 0
		}
		c[0] = n[0]
		for j := 0; j < C; j++ {
			for k := 2; k >= 0; k-- {
				c[k+1] = max(c[k+1], c[k]+goods[i][j])
			}
			for k := 0; k < 4; k++ {
				n[j] = max(n[j], c[k])
			}
			c[0] = max(c[0], n[j+1])
		}
	}

	result := -1
	for k := 0; k < 4; k++ {
		result = max(result, c[k])
	}

	println(result)
}

const (
	ioBufferSize = 1 * 1024 * 1024 // 1 MB
)

var stdinScanner = func() *bufio.Scanner {
	result := bufio.NewScanner(os.Stdin)
	result.Buffer(make([]byte, ioBufferSize), ioBufferSize)
	result.Split(bufio.ScanWords)
	return result
}()

func readString() string {
	stdinScanner.Scan()
	return stdinScanner.Text()
}

func readInt() int {
	result, err := strconv.Atoi(readString())
	if err != nil {
		panic(err)
	}
	return result
}

var stdoutWriter = bufio.NewWriter(os.Stdout)

func flush() {
	stdoutWriter.Flush()
}

func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(stdoutWriter, args...)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func main() {
	defer flush()

	R := readInt()
	C := readInt()
	K := readInt()

	goods := make([][]int, R)
	for i := 0; i < R; i++ {
		goods[i] = make([]int, C)
	}
	for i := 0; i < K; i++ {
		r := readInt() - 1
		c := readInt() - 1
		v := readInt()
		goods[r][c] = v
	}

	n := make([]int, C+1)
	c := make([]int, 4)
	for i := 0; i < R; i++ {
		for k := 0; k < 4; k++ {
			c[k] = 0
		}
		c[0] = n[0]
		for j := 0; j < C; j++ {
			for k := 2; k >= 0; k-- {
				c[k+1] = max(c[k+1], c[k]+goods[i][j])
			}
			for k := 0; k < 4; k++ {
				n[j] = max(n[j], c[k])
			}
			c[0] = max(c[0], n[j+1])
		}
	}

	result := -1
	for k := 0; k < 4; k++ {
		result = max(result, c[k])
	}

	println(result)
}

const (
	ioBufferSize = 1 * 1024 * 1024 // 1 MB
)

var stdinScanner = func() *bufio.Scanner {
	result := bufio.NewScanner(os.Stdin)
	result.Buffer(make([]byte, ioBufferSize), ioBufferSize)
	result.Split(bufio.ScanWords)
	return result
}()

func readString() string {
	stdinScanner.Scan()
	return stdinScanner.Text()
}

func readInt() int {
	result, err := strconv.Atoi(readString())
	if err != nil {
		panic(err)
	}
	return result
}

var stdoutWriter = bufio.NewWriter(os.Stdout)

func flush() {
	stdoutWriter.Flush()
}

func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(stdoutWriter, args...)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var scanner = bufio.NewScanner(os.Stdin)

func NextStr() string {
	scanner.Scan()
	return scanner.Text()
}

func NextInt() int {
	i, _ := strconv.Atoi(NextStr())
	return i
}

func Max(x ...int) int {
	res := x[0]
	for _, a := range x {
		if res < a {
			res = a
		}
	}
	return res
}

func main() {
	scanner.Split(bufio.ScanWords)
	R, C, K := NextInt(), NextInt(), NextInt()
	V := make([][]int, R)
	for i := 0; i < R; i++ {
		V[i] = make([]int, C)
	}

	for i := 0; i < K; i++ {
		r, c, v := NextInt(), NextInt(), NextInt()
		V[r-1][c-1] = v
	}

	// rows := make([]int, R)

	dp := make([][][]int, R)
	for i := 0; i < R; i++ {
		dp[i] = make([][]int, C)
		for j := 0; j < C; j++ {
			dp[i][j] = make([]int, 4)
		}
	}

	dp[0][0][0] = 0
	dp[0][0][1] = V[0][0]

	for i := 0; i < R; i++ {
		for j := 0; j < C; j++ {
			//  first item for the row
			for k := 0; k < 4; k++ {
				switch k {
				case 0:
					if i > 0 {
						dp[i][j][k] = Max(dp[i-1][j][k], dp[i][j][k])
					}
					if j > 0 {
						dp[i][j][k] = Max(dp[i][j-1][k], dp[i][j][k])
					}
				case 1, 2, 3:
					if i > 0 {
						for n := 0; n < 4; n++ {
							dp[i][j][k] = Max(dp[i-1][j][k], dp[i-1][j][n]+V[i][j], dp[i-1][j][n], dp[i][j][k])
						}
					}
					if j > 0 {
						dp[i][j][k] = Max(dp[i][j-1][k], dp[i][j-1][k-1]+V[i][j], dp[i][j][k])
					}
				}
			}
		}
	}
	fmt.Println(Max(dp[R-1][C-1]...))
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func nextFloat64() float64 {
	sc.Scan()
	i, e := strconv.ParseFloat(sc.Text(), 64)
	if e != nil {
		panic(e)
	}
	return i
}

func nextString() string {
	sc.Scan()
	return sc.Text()
}

func abs(x int) int {
	if x < 0 {
		return -1 * x
	} else {
		return x
	}
}

func max(x, y int) int {
	if x > y {
		return x
	} else {
		return y
	}
}

func main() {
	sc.Split(bufio.ScanWords)
	r, c, k := nextInt(), nextInt(), nextInt()

	point := make(map[int]map[int]int)

	for i := 0; i < k; i++ {
		rs, cs, vs := nextInt(), nextInt(), nextInt()

		rs -= 1
		cs -= 1

		if point[rs] == nil {
			tmp := map[int]int{}
			tmp[cs] = vs
			point[rs] = tmp
		} else {
			point[rs][cs] = vs
		}
	}

	dp := make([][][4]int, r+1)
	for i := 0; i < r+1; i++ {
		dp[i] = make([][4]int, c+1)
	}
	dp[0][0][1] = point[0][0]

	for i := 0; i < r; i++ {
		for j := 0; j < c; j++ {
			for p := 0; p < 4; p++ {
				dp[i][j+1][p] = max(dp[i][j+1][p], dp[i][j][p])
				dp[i+1][j][0] = max(dp[i+1][j][0], dp[i][j][p])
				dp[i+1][j][1] = max(dp[i+1][j][1], dp[i][j][p]+point[i+1][j])
				if p+1 < 4 {
					dp[i][j+1][p+1] = max(dp[i][j+1][p+1], dp[i][j][p]+point[i][j+1])
				}
			}
		}
	}

	ans := 0
	for k := 0; k < 4; k++ {
		ans = max(ans, dp[r-1][c-1][k])
	}
	fmt.Println(ans)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

const (
	initialBufSize = 100000
	maxBufSize     = 10000000
)

var (
	sc = bufio.NewScanner(os.Stdin)
	wt = bufio.NewWriter(os.Stdout)
)

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	i, _ := strconv.Atoi(next())
	return i
}

func puts(a ...interface{}) {
	fmt.Fprintln(wt, a...)
}

func max(nums ...int) int {
	ret := nums[0]
	for _, v := range nums {
		if v > ret {
			ret = v
		}
	}
	return ret
}

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, initialBufSize), maxBufSize)
	defer wt.Flush()

	r, c, k := nextInt(), nextInt(), nextInt()
	item := make([][]int, r)
	for i := 0; i < r; i++ {
		item[i] = make([]int, c)
	}
	for i := 0; i < k; i++ {
		ri, ci, v := nextInt()-1, nextInt()-1, nextInt()
		item[ri][ci] = v
	}

	dp := make([][][]int, r)
	for i := range dp {
		dp[i] = make([][]int, c)
		for j := range dp[i] {
			dp[i][j] = make([]int, 4)
		}
	}
	dp[0][0][1] = item[0][0]
	for i := 0; i < r; i++ {
		for j := 0; j < c; j++ {
			for k := 0; k <= 3; k++ {
				if i-1 >= 0 {
					dp[i][j][0] = max(dp[i][j][0], dp[i-1][j][k])
					dp[i][j][1] = max(dp[i][j][1], dp[i-1][j][k]+item[i][j])
				}
				if j-1 >= 0 {
					dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k])
					if k > 0 {
						dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k-1]+item[i][j])
					}
				}
			}
		}
	}

	ans := max(dp[r-1][c-1]...)
	puts(ans)
}
//  [ruby]
class ST
	def initialize n,iv
		@l = (1<<(n-1).bit_length)-1
		@h = [iv]*(@l+@l+1)
	end

	def max
		return @h[0]
	end

	def [] l,r
		return if r < l
		l,r = @l+l+1,@l+r+1
		lx,rx = @h[l-1],@h[r-1]
		while l <= r
			lx = @h[l-1] if lx < @h[l-1]
			rx = @h[r-1] if rx < @h[r-1]
			l = (l+1)/2
			r = (r-1)/2
		end
		return lx < rx ? rx : lx
	end

	def []= i,v
		j = @l+i+1
		@h[j-1] = v
		@h[j-1] = v while 0 < (j/=2) && @h[j-1] < v
		return v
	end
end

(R,C,K),*RCV = $<.map{|ln| ln.split.map(&:to_i) }

Rs = Array.new(R){ [] }
RCV.each{|s,d,v|
	Rs[s-1] << [d-1,v]
}

r0 = ST.new C,0
while r = Rs.shift
	r.empty? and next or r.sort!

	c0,vs = 0,[0]*4
	until r.empty?
		c,v = r.shift
		r0c = r0[c0,c]
		vs[0] = r0c if vs[0] < r0c
		vs[3] = vs[2]+v if vs[3] < vs[2]+v
		vs[2] = vs[1]+v if vs[2] < vs[1]+v
		vs[1] = vs[0]+v if vs[1] < vs[0]+v
		r0[c] = vs.max
		c0 = c+1
	end
end

p r0.max
//  [ruby]
# Studying https://atcoder.jp/contests/abc175/submissions/16084621

(R,C,K),*RCV = $<.map{|ln| ln.split.map(&:to_i) }

Rs = Array.new(R){ [] }
RCV.each{|s,d,v|
	Rs[s-1] << [d-1,v]
}

r0 = [0]*C
while r = Rs.shift
	r.empty? and next or r.sort!

	vs = [0]*4
	until r.empty?
		c,v = r.shift
		vs[0] = r0[c]
		vs[3] = vs[2]+v if vs[3] < vs[2]+v
		vs[2] = vs[1]+v if vs[2] < vs[1]+v
		vs[1] = vs[0]+v if vs[1] < vs[0]+v
		r0[c] = vs.max
	end

	c = 0
	r0[c] = r0[c-1] if r0[c] < r0[c-1] while C > c+=1
end

p r0[-1]
//  [ruby]
(R,C,K),*RCV = $<.map{|ln| ln.split.map(&:to_i) }

Rs = Array.new(R){ [] }
RCV.each{|s,d,v|
	Rs[s-1] << [d-1,v]
}

r0 = [0]*C
while r = Rs.shift
	r.empty? and next or r.sort!

	c0,vs = 0,[0]*4
	until r.empty?
		c,v = r.shift
		vs[0] = [vs[0],r0[(c0..c).max_by{|i|r0[i]}]].max
		vs[3] = vs[2]+v if vs[3] < vs[2]+v
		vs[2] = vs[1]+v if vs[2] < vs[1]+v
		vs[1] = vs[0]+v if vs[1] < vs[0]+v
		r0[c] = vs.max
		c0 = c+1
	end
end

p r0.max
//  [ruby]
r, c, k = gets.split.map(&:to_i)

v = Hash.new{|h,k| h[k] = {}}
k.times do
    i, j, vv = gets.split.map(&:to_i)
    v[i][j] = vv
end

dp = Array.new(c+1) {Array.new(4,0)}
s = Array.new(c+1) {Array.new(4,0)}

1.upto(r) do |i|
    1.upto(c) do |j|
        vv = v[i][j]

        dp[j][0] = dp[j-1][0] if dp[j][0] < dp[j-1][0]
        dp[j][1,3] = dp[j-1][1,3]
        3.downto(1) {|m| dp[j][m] = dp[j][m-1] + vv if dp[j][m] < dp[j][m-1] + vv} if vv

        s[j][0] = dp[j].max
    end
    dp, s = s, dp
end

p dp[c][0]
//  [ruby]
R,C,K = gets.chomp.split(" ").map(&:to_i)
r,c,v = K.times.map{gets.split.map(&:to_i)}.transpose
value = Array.new(R){Array.new(C,0)}
K.times do |i|
  value[r[i]-1][c[i]-1] = v[i]
end
#２つのdp配列を使いまわす
dp0 = Array.new(C+1){Array.new(4,0)}
dp1 = Array.new(C+1){Array.new(4,0)}
R.times do |i|
  C.times do |j|
    #今いるマスを1つずつ処理
    v = value[i][j]
    if v != 0
      #もらうDP、やる必要のない処理(1つもアイテムを取得してないのに3を計算するみたいな)も入ってる
      dp0[j][3] = [dp0[j][3],dp0[j][2]+v].max
      dp0[j][2] = [dp0[j][2],dp0[j][1]+v].max
      dp0[j][1] = [dp0[j][1],dp0[j][0]+v].max
    end
    #次の行にうつるとき、その列での最大値を渡す
    dp1[j][0] = dp0[j].max
    #次のマスへの受け渡し
    dp0[j+1][0] = dp0[j][0] if dp0[j+1][0] < dp0[j][0] #0の遷移のときは列も考慮する必要がある
    dp0[j+1][1] = dp0[j][1]
    dp0[j+1][2] = dp0[j][2]
    dp0[j+1][3] = dp0[j][3]
  end
  #配列の使いまわし
  dp0,dp1 = dp1,dp0
end
puts dp0[C-1][0]
//  [ruby]
GC.disable

(R, C, K), *RCVs = readlines.map{_1.split.map(&:to_i)}

a = RCVs.each_with_object(Array.new(R + 1){Array.new(C + 1, nil)}){|(r, c, v), a| a[r][c] = v}
dp, dp1 = Array.new(C + 2){Array.new(4, 0)}, Array.new(C + 2){Array.new(4, 0)}
(1 .. R).each do |i|
  (1 .. C).each do |j|
    v = a[i][j]
    3.downto(1){|k| dp[j][k] = dp[j][k - 1] + v if dp[j][k] < dp[j][k - 1] + v} if v
    dp1[j][0] = dp[j].max
    dp[j + 1][0] = dp[j][0] if dp[j + 1][0] < dp[j][0]
    dp[j + 1][1, 3] = dp[j][1, 3]
  end
  dp, dp1 = dp1, dp
end
puts dp[C][0]
//  [rust]
use proconio::input;

#[allow(unused_imports)]
use proconio::marker::{Bytes, Chars, Usize1};
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::ops::*;

#[derive(Clone, Debug, Default)]
struct Struct;


//#[proconio::fastout]
fn main() {
    input! {
        r: usize,
        c: usize,
        k: usize,
        mut v0: [(usize,usize,u64);k],
    }

    let mut v = vec![vec![0u64;c+1];r+1];
    for (rr,cc,vv) in v0 {
        v[rr][cc] = vv;
    }
    //
    let mut dp = vec![0u64;c+1];
    let mut dp0 = vec![0u64;c+1];
    let mut dp1 = vec![0u64;c+1];
    let mut dp2 = vec![0u64;c+1];
    let mut dp3 = vec![0u64;c+1];
    for i in 1..=r {
        for j in 1..=c {
            if v[i][j] != 0 {
                dp0[j] = max(dp0[j-1],dp[j]);
                dp1[j] = max(dp1[j-1],max(dp0[j-1],dp[j])+v[i][j]);
                dp2[j] = max(dp2[j-1],dp1[j-1]+v[i][j]);
                dp3[j] = max(dp3[j-1],dp2[j-1]+v[i][j]);
            } else {
                dp0[j] = max(dp0[j-1],dp[j]);
                dp1[j] = dp1[j-1];
                dp2[j] = dp2[j-1];
                dp3[j] = dp3[j-1];
            }
        }

        for j in 1..=c {
            dp[j] = max(max(dp0[j],dp1[j]),max(dp2[j],dp3[j]));
        }
    }

    println!("{}", dp[c]);
}
//  [rust]
use proconio::marker::Usize1;
fn main() {
    proconio::input! {
        r: usize,
        c: usize,
        k: usize,
        rcv: [(Usize1,Usize1,i64);k],
    }
    let mut g=vec![vec![0;c];r];
    for (r,c,v) in rcv {
        g[r][c]=v;
    }
    let mut dp=vec![vec![0;3];c];
    for i in 0..r {
        for j in 0..c {
            let w=g[i][j];
            for k in 0..3 {
                let mut v=w+dp[j][2];
                if j>0 {
                    v=v.max(dp[j-1][k]);
                    if k>0 && w!=0 {
                        v=v.max(dp[j-1][k-1]+w);
                    }
                }
                dp[j][k]=v;
            }
        }
    }
    println!("{}",dp[c-1][2]);
}