Función divertida#8304

Función divertida (Editorial)

Implement a recursive function with memoization.

Algorithm implementation

Declare a two-dimensional array to store the function values: dp[x][y] = f(x, y).

long long dp[51][51];

Implement the recursive function f with memoization.

long long f(int x, int y)
{
  if (x <= 0 || y <= 0) return 0;
  if (dp[x][y] != -1) return dp[x][y];
  if (x <= y) return dp[x][y] = f(x - 1, y - 2) + f(x - 2, y - 1) + 2;
  return dp[x][y] = f(x - 2, y - 2) + 1;
}

The main part of the program. Read the input data.

scanf("%d %d",&x,&y);

Initialize the cells of the array with the value .

memset(dp,-1,sizeof(dp));

Call the function f(x, y) and print its value.

printf("%lld\n",f(x,y));

Python implementation

Implement the recursive function f with memoization.

def f(x, y):
  if x <= 0 or y <= 0: return 0
  if dp[x][y] != -1: return dp[x][y]
  if x <= y:
    dp[x][y] = f(x - 1, y - 2) + f(x - 2, y - 1) + 2
  else:
    dp[x][y] = f(x - 2, y - 2) + 1
  return dp[x][y]

The main part of the program. Read the input data.

x, y = map(int, input().split())

Declare a two-dimensional list to store the function values: dp[x][y] = f(x, y). Initialize the cells of the list with the value .

dp = [[-1] * 51 for _ in range(51)]

Call the function f(x, y) and print its value.

print(f(x, y))