中級 1件解決済み 正答率100.0%

Two Nonattacking Knights

Count safe placements of two knights for each square board size.

このチャレンジで学べること

  • Count all placements with combinations
  • Subtract the attacking positions
  • Derive a closed formula for each board size

問題

翻訳を表示

For each board size k from 1 through n, count unordered pairs of distinct squares on a k by k board where two knights cannot attack each other. A knight moves two squares in one axis and one in the other.

. x . x .
x . . . x
. . K . .
x . . . x
. x . x .

K marks a knight and x its possible destinations, when those squares lie on the board. Swapping the two knights does not create another placement.

Implement two_knights(n).

Input

n: The largest board size to consider.

Output

Return n counts in order, for board sizes 1 through n.

制約

1 ≤ n ≤ 10,000. Counts fit signed 64-bit integers.

例

例 1
入力:
n = 3

期待される出力:
expected = [0, 6, 28]
入力:
long long n = 3;

期待される出力:
std::vector<long long> expected = {0, 6, 28};
入力:
long n = 3;

期待される出力:
long[] expected = new long[] {0, 6, 28};

解説

A 1 × 1 board cannot hold two knights. A 2 × 2 board has six pairs and no attacks. A 3 × 3 board has 36 pairs, of which eight attack, leaving 28.

例 2
入力:
n = 1

期待される出力:
expected = [0]
入力:
long long n = 1;

期待される出力:
std::vector<long long> expected = {0};
入力:
long n = 1;

期待される出力:
long[] expected = new long[] {0};

解説

Two distinct squares are required, but the board has only one.

解き方のヒント

まずは自分で考えてから、ヒントを1つずつ開いてみましょう。

ヒント 1

Start with all unordered pairs of squares on each board, then subtract the pairs where knights attack.

ヒント 2

Only a small, fixed number of knight attack placements fit inside any 2 by 3 or 3 by 2 rectangle.

ヒント 3

Edge boards like 1 by 1 and 2 by 2 need to naturally produce zero attacking pairs.

目安の計算量

O(n) time, O(1) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 Н"Никита "Programmer" Python 823 ms - 5/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意: この下に解答が1件あります まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。