Topics

We are given a recursive construction where a level‑0 burger is just a patty, and for any , a level‑ burger consists of a bun, a level‑ burger, a patty, another level‑ burger, and a bun. Print the number of patties in the bottom-most  layers from the bottom of a level- burger.

Idea

Let be the total number of layers and the total number of patties in a level‑ burger. It is straightforward to prove that

These recurrences allow us to precompute the total layers and patties for each burger up to the given level.

To solve the problem, we define a recursive function that computes the number of patties in the first layers of a level‑ burger. The idea is to simulate the burger’s construction: if , we return 0 (or 1 in the base case when ); if , we return directly; otherwise, we decide whether falls in the lower level‑ burger, hits the middle patty, or lies in the latter level‑ burger. More precisely, if

the answer is the same as in the lower burger (after discounting the initial bun), if

we add the patties from the first level‑ burger plus one for the middle patty, and if

we add the patties from the first half and the middle, and then recursively compute the result for the remaining layers. This careful case analysis—including the crucial check for , ensures correctness even for edge cases.

Time Complexity:
Space Complexity:

Code

vector<pair<ll, ll>> dp(51, make_pair(0, 0));
 
void precomp_layer_counts(int n) {
  // can also be done iteratively as well
  if (n == 0) {
    dp[n] = make_pair(1, 1);
    return;
  }
 
  precomp_layer_counts(n - 1);
  pair<ll, ll> prev = dp[n - 1];
  dp[n] = make_pair(3 + 2 * prev.first, 1 + 2 * prev.second);
}
 
ll burgers(int n, ll x) {
  // base cases
  if (x == dp[n].first)
    return dp[n].second;
 
  if (x == 1)
    return n == 0 ? 1 : 0;
 
  pair<ll, ll> prev = dp[n - 1];
  // x is right at the middle
  if (prev.first + 2 == x)
    return prev.second + 1;
  // x is within first half
  else if (prev.first + 2 > x)
    return burgers(n - 1, x - 1);
  // x is within second half
  else {
    // patties in previous layer + middle patty + patties in rest half
    // rest half = x - (first half layers + 1 for 1st bun + 1 for mid patty)
    return prev.second + 1 + burgers(n - 1, x - prev.first - 2);
  }
}
 
void solve() {
  int n;
  ll a;
  cin >> n >> a;
 
  precomp_layer_counts(n);
  ll res = burgers(n, a);
  cout << res << endl;
}