チャレンジ一覧に戻る
難しい 0件解決済み 正答率0%

Cut a Rectangle Into Squares

Find the fewest straight cuts needed to produce only squares.

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

  • Define a DP table over width and height
  • Try every horizontal and vertical cut
  • Reuse results for smaller rectangles

問題

翻訳を表示

On each move, choose one rectangle and cut all the way across it, parallel to a side, making two rectangles with positive integer side lengths. Continue until every piece is a square. Squares may have different sizes. Count cuts, not pieces.

Implement rectangle_cutting(height, width).

Input

height: The starting rectangle height.

width: The starting rectangle width.

Output

Return the minimum number of cuts.

制約

1 ≤ height, width ≤ 500. Rotation does not change the answer.

例

例 1
入力:
width = 3
height = 2

期待される出力:
expected = 2
入力:
long long width = 3;
long long height = 2;

期待される出力:
long long expected = 2;
入力:
long width = 3;
long height = 2;

期待される出力:
long expected = 2;

解説

Cut off a 2 × 2 square, leaving a 2 × 1 rectangle. One more cut splits the remainder into two unit squares.

例 2
入力:
width = 4
height = 4

期待される出力:
expected = 0
入力:
long long width = 4;
long long height = 4;

期待される出力:
long long expected = 0;
入力:
long width = 4;
long height = 4;

期待される出力:
long expected = 0;

解説

The starting rectangle is already a square.

解き方のヒント

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

ヒント 1

A rectangle can be solved by splitting it into two smaller rectangles and combining their best answers.

ヒント 2

Try every possible horizontal and vertical cut to find the minimum.

ヒント 3

Memoization or a table is helpful because many subrectangles repeat.

目安の計算量

O(h*w*(h+w)) time, O(h*w) extra space

参考資料

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

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。