题解:AT_joi2024_yo1b_d 繰り返し (Repetition)

· · 题解

chen_zhe 说不能直接写依题意模拟,那我来把题意复述一遍。

若

循环直到 x\geqslant N,输出循环次数。

#include <bits/stdc++.h>
using namespace std;

int main() {
  cin.tie(nullptr)->sync_with_stdio(false);
  cin.exceptions(cin.failbit | cin.badbit);
  int32_t x, n;
  cin >> x >> n;
  size_t cnt = 0;
  for (; x < n; ++cnt) {
    switch (x % 3) {
    case 0:
      ++x;
      break;
    case 1:
      x *= 2;
      break;
    case 2:
      x *= 3;
      break;
    }
  }
  cout << cnt << '\n';
  return 0;
}

先分析一下复杂度,注意到:

简单来讲,有一个形如下的自动机:

\begin{aligned} 0 \to 1 \\ 1 \to 2 \\ 2 \to 0 \end{aligned}

显然每操作 3 次后 x 至少变为 6x,因此总操作次数是 \mathcal O\left(\log N\right) 的。

我们还能写出递归做法:

size_t solve(int32_t x, int32_t n) {
  if (x >= n)
    return 0;
  if (x % 3 == 0)
    return solve(x + 1, n) + 1;
  if (x % 3 == 1)
    return solve(x * 2, n) + 1;
  if (x % 3 == 2)
    return solve(x * 3, n) + 1;
  __builtin_unreachable();
}