根据题意,我们可以列出如下的方程组:

$$\begin{cases}x\equiv1\pmod2\x\equiv2\pmod3\x\equiv4\pmod5\x\equiv5\pmod6\x\equiv0\pmod7\end{cases}$$

其中 $x$ 表示阶梯的总台阶数。我们可以使用中国剩余定理来求解这个方程组。

首先,由于 $7$ 是一个质数,所以对于最后一个方程,我们可以直接使用逆元来求解:

$$x\equiv0\pmod7\Rightarrow x=7k$$

$$\begin{aligned}&5\times3\equiv1\pmod7\&5\times2\equiv4\pmod7\&2\times3\equiv1\pmod5\&2\times5\equiv1\pmod3\end{aligned}$$

因此,我们可以将前四个方程组合并,得到:

$$x=30a+22$$

其中 $a$ 为任意整数。

最后,我们将 $x=7k$ 和 $x=30a+22$ 代入 $x\leq N$,得到所有满足条件的阶梯。具体做法是,先找到最小的 $k$,使得 $7k>N$,然后在 $0\leq a < \frac{N-22}{30}$ 的范围内枚举 $a$,计算出所有满足条件的 $x$。

以下是 Python 代码实现:

def CRT(a, b, c, d, e):
    M1, M2, M3, M4 = 3 * 5 * 7, 2 * 5 * 7, 2 * 3 * 7, 2 * 3 * 5
    r1, r2, r3, r4 = 1, 1, 1, 1
    while True:
        if (r1 * M1) % 2 == a and (r1 * M1) % 3 == b and (r1 * M1) % 5 == c and (r1 * M1) % 7 == 0:
            return r1 * M1 + e
        if (r2 * M2) % 3 == b and (r2 * M2) % 5 == c and (r2 * M2) % 7 == 0:
            return r2 * M2 + e
        if (r3 * M3) % 5 == c and (r3 * M3) % 7 == 0:
            return r3 * M3 + e
        if (r4 * M4) % 7 == 0:
            return r4 * M4 + e
        r1 += 1
        r2 += 1
        r3 += 1
        r4 += 1

n = int(input())
ans = []
for k in range(1, n // 7 + 2):
    x = 7 * k
    for a in range((n - 22) // 30 + 1):
        x = CRT(x % 2, x % 3, x % 5, x % 6, 5)
        if x > n:
            break
        if x not in ans:
            ans.append(x)

print(len(ans))
print(*ans)

时间复杂度为 $O(\frac{N}{210}\log N)$。

爱因斯坦的阶梯:求解阶梯总台阶数的算法

原文地址: https://www.cveoy.top/t/topic/mJ6j 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录