CSES - Shared codeLink to this code:
https://cses.fi/paste/ba9b8b98433cf5055cb26d/
#include <bits/stdc++.h>
#define ll long long
#define F first
#define S second
#define pll pair<long long, long long>
#define pii pair<int, int>
#define mii map <int , int>
#define mll map <long long ,long long>
#define vi vector <int>
#define vl vector <long long>
#define pb push_back
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define cmp greater<int>()
#define RF(F) freopen(F , "r" , stdin )
#define WF(F) freopen(F , "w" , stdout)
using namespace std;
const ll INF = 1e9 ;
const int N = 500 + 7 ;
const int mod = 1e9 + 7;
int mem[N][N] ;
string get_string() {
const int N = 2e5 + 7 ;
char s[N] ;
scanf("%s" , s) ;
return s ;
}
void init() {
memset(mem , -1 , sizeof mem) ;
}
int dp(int n , int m){
if(n == m)return 0 ;
if(m == 1)return n - 1 ;
if(n == 1)return m - 1 ;
if(mem[n][m] != -1)return mem[n][m] ;
int ans = INF ;
for(int i = 1 ; i <= (n / 2) ; i ++){
ans = min(ans , 1 + dp(i , m) + dp(n - i , m)) ;
}
for(int j = 1 ; j <= (m / 2) ; j ++){
ans = min(ans , 1 + dp(n , j) + dp(n , m - j)) ;
}
return mem[n][m] = ans ;
}
void solve(int testCase){
int n , m ;
scanf("%d %d" , &n , &m) ;
printf("%d" , dp(n , m)) ;
}
int main() {
int testCase = 1;
//scanf("%d", &testCase);
while (testCase--){
init();
solve(testCase);
}
return 0;
}