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

Solution in Rust (1.42.0) (judge verdict: Runtime Error)

use io_ext::Reader;
use parse::ParseAll;
use std::io;

fn main() {
    let stdin = io::stdin();
    let mut r = Reader::new(stdin.lock());
    let (rows, cols, k): (usize, usize, usize) = r.read_line().split_whitespace().parse_all();
    let mut vals: Vec<Vec<i64>> = Vec::with_capacity(rows);
    for _ in 0..rows {
        let row = r.read_line().split_whitespace().parse_all();
        vals.push(row);
    }
    println!("{}", answer(rows, cols, &vals, k));
}

fn chmax<T: PartialOrd>(x: &mut T, y: T) {
    if *x < y {
        *x = y
    }
}

fn answer(rows: usize, cols: usize, vals: &[Vec<i64>], _k: usize) -> i64 {
    let mut dp = vec![vec![vec![-1; 4]; cols]; rows];
    dp[0][0][0] = 0;

    for i in 0..rows {
        for j in 0..cols {
            for k in (0..3).rev() {
                if dp[i][j][k] >= 0 {
                    let x = dp[i][j][k] + vals[i][j];
                    chmax(&mut dp[i][j][k + 1], x);
                }
            }

            for k in 0..4 {
                if dp[i][j][k] >= 0 {
                    if i + 1 < rows {
                        let x = dp[i][j][k];
                        chmax(&mut dp[i + 1][j][0], x);
                    }
                    if j + 1 < cols {
                        let x = dp[i][j][k];
                        chmax(&mut dp[i][j + 1][k], x);
                    }
                }
            }
        }
    }

    let mut ans = 0;
    for k in 0..4 {
        ans = ans.max(dp[rows - 1][cols - 1][k]);
    }

    ans
}

#[cfg(test)]
mod tests {
    use super::answer;

    #[test]
    fn test() {}
}

pub mod int_ext {
    pub fn digits10(n: i64) -> i64 {
        assert!(n >= 0);

        let mut d = 1;
        let mut p = 10;
        while p <= n {
            p *= 10;
            d += 1;
        }
        d
    }

    pub fn permutation(n: i64, k: i64) -> i64 {
        assert!(k >= 0);
        assert!(n >= k);

        let mut p = 1;
        for i in 0..k {
            p = p * (n - i);
        }
        p
    }

    pub fn combination(n: i64, k: i64) -> i64 {
        use std::cmp;

        assert!(k >= 0);
        assert!(n >= k);

        let k = cmp::min(k, n - k);
        let num = permutation(n, k);
        let mut den = 1;
        for i in 0..k {
            den = den * (i + 1);
        }
        num / den
    }
}

/// A module for easy use of io.
pub mod io_ext {
    use std::io::BufRead;

    pub struct Reader<R> {
        buf: String,
        inner: R,
    }

    impl<R> Reader<R> {
        #[inline]
        pub fn new(inner: R) -> Self {
            Reader {
                buf: String::new(),
                inner: inner,
            }
        }

        #[inline]
        pub fn into_inner(self) -> R {
            self.inner
        }
    }

    impl<R: BufRead> Reader<R> {
        #[allow(deprecated)]
        #[inline]
        pub fn read_line(&mut self) -> &str {
            self.buf.clear();
            self.inner
                .read_line(&mut self.buf)
                .unwrap_or_else(|e| panic!("{}", e));
            self.buf.trim_right()
        }
    }
}

/// Parsing Iterator.
pub mod parse {
    use std::borrow::Borrow;
    use std::str::FromStr;

    pub trait FromStrIterator {
        fn from_str_iter<S: Borrow<str>, I: Iterator<Item = S>>(i: I) -> Self;
    }

    pub trait ParseAll {
        fn parse_all<F: FromStrIterator>(self) -> F;
    }

    impl<S: Borrow<str>, I: Iterator<Item = S>> ParseAll for I {
        #[inline]
        fn parse_all<F: FromStrIterator>(self) -> F {
            F::from_str_iter(self)
        }
    }

    fn parse<S: Borrow<str>, I: Iterator<Item = S>, F: FromStr>(i: &mut I) -> F {
        i.next()
            .unwrap_or_else(|| panic!("too few strings error"))
            .borrow()
            .parse()
            .unwrap_or_else(|_| panic!("parse error"))
    }

    // To avoid conflict, this is not implemented for `A` but `(A,)`.
    impl<A: FromStr> FromStrIterator for (A,) {
        fn from_str_iter<S: Borrow<str>, I: Iterator<Item = S>>(mut i: I) -> Self {
            let a = parse(&mut i);
            if i.next().is_some() {
                panic!("too many strings error");
            }
            (a,)
        }
    }

    impl<A: FromStr, B: FromStr> FromStrIterator for (A, B) {
        fn from_str_iter<S: Borrow<str>, I: Iterator<Item = S>>(mut i: I) -> Self {
            let a = parse(&mut i);
            let b = parse(&mut i);
            if i.next().is_some() {
                panic!("too many strings error");
            }
            (a, b)
        }
    }

    impl<A: FromStr, B: FromStr, C: FromStr> FromStrIterator for (A, B, C) {
        fn from_str_iter<S: Borrow<str>, I: Iterator<Item = S>>(mut i: I) -> Self {
            let a = parse(&mut i);
            let b = parse(&mut i);
            let c = parse(&mut i);
            if i.next().is_some() {
                panic!("too many strings error");
            }
            (a, b, c)
        }
    }

    impl<A: FromStr, B: FromStr, C: FromStr, D: FromStr> FromStrIterator for (A, B, C, D) {
        fn from_str_iter<S: Borrow<str>, I: Iterator<Item = S>>(mut i: I) -> Self {
            let a = parse(&mut i);
            let b = parse(&mut i);
            let c = parse(&mut i);
            let d = parse(&mut i);
            if i.next().is_some() {
                panic!("too many strings error");
            }
            (a, b, c, d)
        }
    }

    impl<T: FromStr> FromStrIterator for Vec<T> {
        fn from_str_iter<S: Borrow<str>, I: Iterator<Item = S>>(i: I) -> Self {
            i.map(|s| s.borrow().parse().unwrap_or_else(|_| panic!("parse error")))
                .collect()
        }
    }
}

pub mod modulo {
    /// Returns `x` + `y` mod `modulo`.
    ///
    /// `x < modulo` and `y < modulo` must hold.
    #[inline]
    pub fn add(x: u64, y: u64, modulo: u64) -> u64 {
        debug_assert!(modulo > 0);
        debug_assert!(x < modulo && y < modulo);
        let sum = x as u64 + y as u64;
        if sum <= modulo as u64 {
            sum
        } else {
            sum.wrapping_sub(modulo)
        }
    }

    /// Returns `x` - `y` mod `modulo`.
    ///
    /// `x < modulo` and `y < modulo` must hold.
    #[inline]
    pub fn sub(x: u64, y: u64, modulo: u64) -> u64 {
        debug_assert!(0 < modulo);
        debug_assert!(x < modulo && y < modulo);
        if x >= y {
            x - y
        } else {
            modulo + x - y
        }
    }

    /// Returns `x` * `y` mod `modulo`.
    #[inline]
    pub fn mul(x: u64, y: u64, modulo: u64) -> u64 {
        (x as u64 * y as u64) % modulo as u64
    }

    /// Returns `x`^ `y` mod `modulo`.
    pub fn pow(x: u64, mut y: u64, modulo: u64) -> u64 {
        debug_assert!(0 < modulo);
        let mut p = x;
        let mut ret = 1;

        while y != 0 {
            if y & 1 == 1 {
                ret = mul(ret, p, modulo);
            }
            p = mul(p, p, modulo);
            y >>= 1;
        }
        ret
    }

    fn is_prime(x: u64) -> bool {
        let sqrt = (x as f64).sqrt() as u64;
        for factor in 2..sqrt {
            if x % factor == 0 {
                return false;
            }
        }
        true
    }

    /// Returns 1 / `x`.
    ///
    /// `modulo` must be a prime number.
    #[inline]
    fn reciprocal(x: u64, modulo: u64) -> u64 {
        debug_assert!(0 < modulo && is_prime(modulo));
        pow(x, modulo - 2, modulo)
    }

    /// Returns `x` / `y` mod `modulo`.
    ///
    /// `modulo` must be a prime number.
    #[inline]
    pub fn div(x: u64, y: u64, modulo: u64) -> u64 {
        debug_assert!(0 < modulo && is_prime(modulo));
        mul(x, reciprocal(y, modulo), modulo)
    }

    /// Returns `n`P`k` mod `modulo`.
    pub fn perm(n: u64, k: u64, modulo: u64) -> u64 {
        let mut p = 1;
        for i in 0..k {
            p = mul(p, n - i, modulo);
        }
        p
    }

    /// Returns `n`C`k` mod `modulo`.
    pub fn comb(n: u64, k: u64, modulo: u64) -> u64 {
        let k = if k <= n / 2 { k } else { n - k };
        let num = perm(n, k, modulo);
        let mut den = 1;
        for i in 0..k {
            den = mul(den, i + 1, modulo);
        }
        div(num, den, modulo)
    }
}