日期:2026年4月18日
ZeroJudge 題目連結:d130. 00138 - Street Numbers
解題想法
這題的答案固定為
6 8
35 49
204 288
1189 1681
6930 9800
40391 57121
235416 332928
1372105 1940449
7997214 11309768
46611179 65918161
左側包含起點的和
$$
lsum = \frac{(1+k) \times k}{2}
$$
右側包含起點的和
$$
rsum = \frac{(k+n) \times (n-k+1)}{2}
$$
如果 $lsum = rsum$,則
$$
\begin{align*}
& k(1+k) = (k+n)(n-k+1) \\
~\Rightarrow~& k + k^2 = nk - k^2 + k + n^2 - nk + n \\
~\Rightarrow~& n^2 + n - 2k^2 = 0 \\
~\Rightarrow~& n = \frac{-1 \pm \sqrt{1 + 8k^2}}{2}
\end{align*}
$$
因為 $n, k \in N$ 且 $n>k$,上式的答案只能取加號;$1 + 8k^2$ 是完全平方數,開根號減 1 之後是偶數。
Python 程式碼
這題我沒有寫出正常作法而且可以 AC 的 Python 程式碼,只有直接輸出答案的作弊版,使用時間約為 8 ms,記憶體約為 8.8 MB,通過測試。
import sys
result = [" 6 8\n",
" 35 49\n",
" 204 288\n",
" 1189 1681\n",
" 6930 9800\n",
" 40391 57121\n",
" 235416 332928\n",
" 1372105 1940449\n",
" 7997214 11309768\n",
" 46611179 65918161\n"]
sys.stdout.write("".join(result))
C++ 程式碼
利用數學性質,使用時間約為 96 ms,記憶體約為 1 MB,通過測試。
#include <cstdio>
#include <cmath>
int main() {
int cnt = 0;
long i = 4;
while(cnt < 10) {
long D = i*i;
if ((D-1)%8 != 0) {
i++;
continue;
}
long k_square = (D-1) / 8;
long k_root = (long)sqrt(k_square);
if (k_root*k_root != k_square) {
i++;
continue;
}
if ((i-1)%2 != 0) {
i++;
continue;
}
long n = (i-1)/2;
printf("%10ld%10ld\n", k_root, n);
cnt++;
i++;
}
return 0;
}
直接輸出答案,使用時間約為 0 ms,記憶體約為 1.2 MB,通過測試。
#include <cstdio>
int main() {
puts(" 6 8");
puts(" 35 49");
puts(" 204 288");
puts(" 1189 1681");
puts(" 6930 9800");
puts(" 40391 57121");
puts(" 235416 332928");
puts(" 1372105 1940449");
puts(" 7997214 11309768");
puts(" 46611179 65918161");
return 0;
}
沒有留言:
張貼留言