Problem:
Score : 1000 points

Problem Statement

There are N barbecue restaurants along a street.
The restaurants are numbered 1 through N from west to east, and the distance between restaurant i and restaurant i+1 is A_i.

Joisino has M tickets, numbered 1 through M.
Every barbecue restaurant offers barbecue meals in exchange for these tickets.
Restaurant i offers a meal of deliciousness B_{i,j} in exchange for ticket j.
Each ticket can only be used once, but any number of tickets can be used at a restaurant.

Joisino wants to have M barbecue meals by starting from a restaurant of her choice, then repeatedly traveling to another barbecue restaurant and using unused tickets at the restaurant at her current location.
Her eventual happiness is calculated by the following formula: "(The total deliciousness of the meals eaten) - (The total distance traveled)".
Find her maximum possible eventual happiness.

Constraints

All input values are integers.

2≤N≤5×10^3

1≤M≤200

1≤A_i≤10^9

1≤B_{i,j}≤10^9

Input

The input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_{N-1}
B_{1,1} B_{1,2} ... B_{1,M}
B_{2,1} B_{2,2} ... B_{2,M}
:
B_{N,1} B_{N,2} ... B_{N,M}

Output

Print Joisino's maximum possible eventual happiness.

Sample Input 1

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

Sample Output 1

11

The eventual happiness can be maximized by the following strategy: start from restaurant 1 and use tickets 1 and 3, then move to restaurant 2 and use tickets 2 and 4.

Sample Input 2

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

Sample Output 2

20

Solution in Rust (1.42.0) (judge verdict: Accepted)

use std::cmp::max;
use std::collections::VecDeque;
use std::cmp::min;
use core::ops::Bound::Excluded;
use core::ops::Bound::Included;
use std::collections::BTreeSet;
use std::cmp::Ordering;
use std::fmt::Debug;

fn read_line() -> String {
    let mut buffer = String::new();
    std::io::stdin().read_line(&mut buffer).expect("No Line");
    buffer
}
fn read_lines<R, T: Fn(&str)->R> (count: usize, transformer: T) -> Vec<R> {
    let mut buffer = String::new();
    let mut vec = Vec::with_capacity(count);
    for _ in 0 .. count {
        std::io::stdin().read_line(&mut buffer).expect("No Line");
        vec.push(transformer(buffer.trim()));
        buffer.clear();
    }
    vec
}
fn read_value<T: std::str::FromStr>() -> T {
    read_line().trim().parse().ok().unwrap()
}
fn read_values<T: std::str::FromStr>() -> Vec<T> {
    read_line().trim().split(' ').map(|x| x.parse().ok().expect("Can't Parse")).collect::<Vec<T>>()
}
fn read_tabulate<T: std::str::FromStr>(count: usize) -> Vec<T> {
    let mut buffer = String::new();
    let mut vec = Vec::with_capacity(count);
    for _ in 0 .. count {
        std::io::stdin().read_line(&mut buffer).expect("No Line");
        vec.push(buffer.trim().parse().ok().expect("Can't Parse"));
        buffer.clear();
    }
    vec
}
macro_rules! define {
    () => {};
    ($($token:tt)*) => {
        let mut iter = read_values::<String>().into_iter();
        define_iter!(iter, $($token)*);
    };
}
macro_rules! define_iter {
    ($iter:expr) =>{};
    ($iter:expr,) =>{};
    ($iter:expr, $id:ident:$t:tt $($tail:tt)*) => {
        let $id: $t = $iter.next().unwrap().parse().ok().expect("Can't Parse");
        define_iter!($iter, $($tail)*);
    };
    ($iter:expr, mut $id:ident:$t:tt $($tail:tt)*) => {
        let mut $id: $t = $iter.next().unwrap().parse().ok().expect("Can't Parse");
        define_iter!($iter, $($tail)*)
    };
}
macro_rules! freeze {
    ($($id:ident), *) => {
        $(let $id = $id;)*
    };
}
struct KeyValue<K, V> {
    key: K,
    value: V
}
impl <K: PartialOrd, V> PartialEq for KeyValue<K, V> {
    fn eq(&self, other: &Self) -> bool {
        self.key.eq(&other.key)
    }
}
impl <K: PartialOrd, V> Eq for KeyValue<K, V> {}
impl <K: PartialOrd, V> PartialOrd for KeyValue<K, V> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.key.partial_cmp(&other.key)
    }
}
impl <K: PartialOrd, V> Ord for KeyValue<K, V> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.key.partial_cmp(&other.key).ok_or("Can't Compare").unwrap()
    }
}
fn main() {
    define! {
        n: usize
        m: usize
    }
    let position = read_values::<i64>();
    let restaurants: Vec<Vec<i64>> = read_lines(n, |str| str.split(' ').map(|x| x.parse::<i64>().unwrap()).collect::<Vec<_>>());
    let mut memo: Vec<Vec<i64>> = vec![vec![0i64; n + 1]; n + 1];
    for t in 0 .. m {
        let mut stack = Vec::<usize>::new();
        for (next, restaurant) in restaurants.iter().enumerate() {
            let value = restaurant[t];
            while let Some(&mid) = stack.last() {
                if restaurants[mid][t] <= value {
                    stack.pop();
                    if let Some(&prev) = stack.last() {
                        memo[prev + 1][mid] += restaurants[mid][t];
                        memo[mid + 1][next] += restaurants[mid][t]; 
                        memo[mid + 1][mid] -= restaurants[mid][t];
                        memo[prev + 1][next] -= restaurants[mid][t];
                    }else {
                        memo[0][mid] += restaurants[mid][t];
                        memo[mid + 1][next] += restaurants[mid][t];
                        memo[mid + 1][mid] -= restaurants[mid][t];
                        memo[0][next] -= restaurants[mid][t];
                    }
                }else {
                    break;
                }
            }
            stack.push(next);
        }
        while let Some(mid) = stack.pop() {
            if let Some(&prev) = stack.last() {
                memo[prev + 1][mid] += restaurants[mid][t];
                memo[mid + 1][n] += restaurants[mid][t];
                memo[mid + 1][mid] -= restaurants[mid][t];
                memo[prev + 1][n] -= restaurants[mid][t];
            }else {
                memo[0][mid] += restaurants[mid][t];
                memo[mid + 1][n] += restaurants[mid][t];
                memo[mid + 1][mid] -= restaurants[mid][t];
                memo[0][n] -= restaurants[mid][t];
            }
        }
    }
    for i in 1 ..= n {
        for j in 0 ..= n {
            memo[i][j] += memo[i - 1][j];
        }
    }
    for i in 0 ..= n {
        for j in 1 ..= n {
            memo[i][j] += memo[i][j - 1];
        }
    }
    let mut diff = vec![0i64];
    for pos in position {
        diff.push(diff.last().unwrap() + pos);
    }
    freeze!(diff);
    let mut result = 0i64;
    for i in 0 .. n {
        for j in i .. n {
            result = max(result, diff[i] - diff[j] + memo[i][j]);
        }
    }
    println!("{}", result);
}