Editorial for LCC '24 Contest 2 S4 - Cookies


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Author: Colin

Subtask 1

Since 1 \leq N \leq 10^6, we can just simulate the cookies.

Time Complexity: O(N)

Subtask 2

Simulating for 1 \leq N \leq 10^{18} panels will TLE. Instead, we can work backwards and use a recursive approach:

Let c(x) be the number of cookies on panel x. Notice that the only previous panels that contribute to the total sum are c(\frac x 2), c(\frac {x-1} 2), and c(\frac x 3). Therefore, c(x) = c(\frac x 2) + c(\frac {x-1} 2) + c(\frac x 3), with c(x) = 0 for noninteger x. It turns out that c(x) is fast enough to AC!

#include <stdio.h>

int f(long x) {
  if (x < 2) {
    return x;
  } else {
    return f(x / 2) + (x % 3 == 0 ? f(x / 3) : 0);
  }
}

int main() {
  long n;
  scanf("%ld", &n);
  printf("%d\n", f(n));
}

(note how c(\frac x 2) + c(\frac {x-1} 2) is collapsible into c(\lfloor \frac x 2 \rfloor).)

Time Complexity: O(log N), probably


Comments

There are no comments at the moment.