#include using namespace std; using ll = long long; #define CIN( LL , A ) LL A; cin >> A #define UNTIE ios_base::sync_with_stdio( false ); cin.tie( nullptr ) #define FOR( VAR , INITIAL , FINAL_PLUS_ONE ) for( remove_const::type >::type VAR = INITIAL ; VAR < FINAL_PLUS_ONE ; VAR ++ ) #define REPEAT( HOW_MANY_TIMES ) FOR( VARIABLE_FOR_REPEAT , 0 , HOW_MANY_TIMES ) #define QUIT return 0 #define RETURN( ANSWER ) cout << ( ANSWER ) << "\n"; QUIT #define MIN( A , B ) ( A < B ? A : B ) int main() { UNTIE; constexpr const int bound_M = 1000; CIN( int , N ); assert( 1 <= N && N <= bound_M ); CIN( int , M ); assert( 1 <= M && M <= bound_M ); int i0 = 0; int i1 = 1; constexpr const ll bound_Aj = 1000000001; ll A[2][bound_M] = {}; ll opt0[2] = {}; ll opt1[2] = {}; ll optn[2][bound_M] = {}; int j0[2] = {}; constexpr const ll bound_opt = 1000000000001; ll opt_up; ll opt_shift; ll opt_total; REPEAT( N ){ ll ( &A_current )[bound_M] = A[i0]; int& j0_current = j0[i0]; ll& opt0_current = opt0[i0]; ll& opt1_current = opt1[i0]; ll ( &optn_current )[bound_M] = optn[i0]; opt0_current = bound_opt; opt0_current = bound_opt; ll ( &A_prev )[bound_M] = A[i1]; const int j0_prev = j0[i1]; ll& opt0_prev = opt0[i1]; ll& opt1_prev = opt1[i1]; ll ( &optn_prev )[bound_M] = optn[i1]; FOR( j , 0 , M ){ ll& Aj = A_current[j]; cin >> Aj; assert( 1 <= Aj && Aj < bound_Aj ); opt_up = optn_prev[j]; opt_shift = ( j == j0_prev ? opt1_prev : opt0_prev ) + A_prev[j]; opt_total = MIN( opt_up , opt_shift ) + Aj; if( opt0_current > opt_total ){ opt1_current = opt0_current; opt0_current = opt_total; j0_current = j; } else if( opt1_current > opt_total ){ opt1_current = opt_total; } optn_current[j] = opt_total; } swap( i0 , i1 ); } RETURN( N == 1 ? 0 : opt0[i1] ); }