Link to this code:
https://cses.fi/paste/b1cad99348e945e18973dd/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
const int INF = 1e9;
const ll LINF = 1e18;
template<typename T>
bool minimize(T& a, const T& b) {
if (a < b) return false;
a = b;
return true;
}
const int N = 5e2 + 5;
int memo[N][N];
int dp(int a, int b) {
if (a == b) return 0;
int& ans = memo[a][b];
if (ans != -1) return ans;
ans = INF;
for (int i = 1; i <= a - 1; i++) {
minimize(ans, 1 + dp(i, b) + dp(a - i, b));
}
for (int j = 1; j <= b - 1; j++) {
minimize(ans, 1 + dp(a, j) + dp(a, b - j));
}
return ans;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int a, b;
cin >> a >> b;
memset(memo, -1, sizeof memo);
cout << dp(a, b) << '\n';
}