#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 opt_all[2] = {}; ll opt_each[2][bound_M] = {}; int j0[2] = {}; constexpr const ll bound_opt = 1000000000001; ll opt_up; ll opt_shift; ll opt_up_shift; REPEAT( N ){ ll ( &A_current )[bound_M] = A[i0]; int& j0_current = j0[i0]; ll& opt_all_current = opt_all[i0]; ll ( &opt_each_current )[bound_M] = opt_each[i0]; opt_all_current = bound_opt; opt_all_current = bound_opt; ll ( &A_prev )[bound_M] = A[i1]; const int j0_prev = j0[i1]; ll& opt_all_prev = opt_all[i1]; ll ( &opt_each_prev )[bound_M] = opt_each[i1]; FOR( j , 0 , M ){ ll& Aj = A_current[j]; cin >> Aj; assert( 1 <= Aj && Aj < bound_Aj ); opt_up = opt_each_prev[j]; opt_shift = opt_all_prev + A_prev[j]; opt_up_shift = MIN( opt_up , opt_shift ) + Aj; if( opt_all_current > opt_up_shift ){ opt_all_current = opt_up_shift; j0_current = j; } opt_each_current[j] = opt_up_shift; } swap( i0 , i1 ); } RETURN( N == 1 ? 0 : opt_all[i1] ); }