#[allow(unused_imports)] use std::cmp::{max, min}; #[allow(unused_imports)] use std::collections::{HashMap, HashSet}; mod util { use std::io::stdin; use std::str::FromStr; use std::fmt::Debug; #[allow(dead_code)] pub fn line() -> String { let mut line: String = String::new(); stdin().read_line(&mut line).unwrap(); line.trim().to_string() } #[allow(dead_code)] pub fn get() -> T where ::Err: Debug, { let mut line: String = String::new(); stdin().read_line(&mut line).unwrap(); line.trim().parse().unwrap() } #[allow(dead_code)] pub fn gets() -> Vec where ::Err: Debug, { let mut line: String = String::new(); stdin().read_line(&mut line).unwrap(); line.split_whitespace() .map(|t| t.parse().unwrap()) .collect() } #[allow(dead_code)] pub fn get2() -> (T, U) where ::Err: Debug, ::Err: Debug, { let mut line: String = String::new(); stdin().read_line(&mut line).unwrap(); let mut iter = line.split_whitespace(); ( iter.next().unwrap().parse().unwrap(), iter.next().unwrap().parse().unwrap(), ) } #[allow(dead_code)] pub fn get3() -> (S, T, U) where ::Err: Debug, ::Err: Debug, ::Err: Debug, { let mut line: String = String::new(); stdin().read_line(&mut line).unwrap(); let mut iter = line.split_whitespace(); ( iter.next().unwrap().parse().unwrap(), iter.next().unwrap().parse().unwrap(), iter.next().unwrap().parse().unwrap(), ) } } #[allow(unused_macros)] macro_rules! debug { ($x: expr) => { println!("{}: {:?}", stringify!($x), $x) } } fn main() { let n: usize = util::get(); let m: usize = util::get(); let a: Vec> = (0..m).map(|_| util::gets()).collect(); let b = 10000; let mut dp = vec![vec![vec![0; m]; b + 1]; m]; for i in 1..b + 1 { for k in 0..m { for s in 0..m { if i == 1 { dp[s][i][k] = a[s][k]; } else { for j in 0..m { dp[s][i][k] = max(dp[s][i][k], dp[s][i - 1][j] + a[j][k]); } } } } } let c = n / b; let rest = n - c * b - 1; let mut dp2 = vec![vec![0; m]; c + 2]; for i in 1..c + 2 { for k in 0..m { if i == c + 1 { for j in 0..m { dp2[i][k] = max(dp2[i][k], dp2[i - 1][j] + dp[j][rest][k]); } } else { for j in 0..m { dp2[i][k] = max(dp2[i][k], dp2[i - 1][j] + dp[j][b][k]); } } } } println!("{}", dp2[c + 1].iter().max().cloned().unwrap()) }