假设slow起始位于N(0),而fast位于N(d - 1)(其中d为一个随机位置) 假设环的长度为M,则t时间后slow位于N(t mod M),而fast位于N((2t + d) mod M) \[\left\{
\begin{aligned}
t = pM + x \\
2t + d = qM + x
\end{aligned}
\right.\] 两式相减 得到t = (q - p)M - d 因此,他们必相遇
Elegant solution. Allow me to explain what is being done here. As per the keyboard operations: to get AA from A we need 2 additional steps (copy-all and then paste) to get AAA from A we need 3 additional steps (copy-all, then paste, then again paste)
For generating AAAA we need 2 additional steps from AA. however, to get AAAAAAAA, the most optimal way would be from AAAA, with 2 additional steps (copy-all then paste) Essentially, we find the next smaller length sequence (than the one under consideration) which can be copied and then pasted over multiple times to generate the desired sequence. The moment we find a length that divides our required sequence length perfectly, then we don't need to check for any smaller length sequences.
// if sequence of length 'j' can be pasted multiple times to get length 'i' sequence if (i % j == 0) { // we just need to paste sequence j (i/j - 1) times, hence additional (i/j) times since we need to copy it first as well. // we don't need checking any smaller length sequences dp[i] = dp[j] + (i/j); break; }
1 2 3
如果找到了一个更短的序列也能被整除,假设第一次找到的为j,第二次找到的为k,则j / k = m,设i / j = n,则i / k = m * n。则dp[j] = dp[k] + m,而dp[i] = dp[j] + n = dp[k] + m * n 则dp[i] = dp[j] + n = dp[k] + m * n = dp[k] + m + n,因为当m > 1 && n > 1时,m+n<mn(mn - (m + n) = (m - 1)(n - 1)),所以第一次遇到的就是最小的结果。 当然,如果不放心的话,也可以用min来遍历