Все задачи
Сложно Решена: 1 Процент решений: 100.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
Ввод:
height = 2
width = 3

Ожидаемый вывод:
expected = 2
Ввод:
long long height = 2;
long long width = 3;

Ожидаемый вывод:
long long expected = 2;
Ввод:
long height = 2;
long width = 3;

Ожидаемый вывод:
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
Ввод:
height = 4
width = 4

Ожидаемый вывод:
expected = 0
Ввод:
long long height = 4;
long long width = 4;

Ожидаемый вывод:
long long expected = 0;
Ввод:
long height = 4;
long width = 4;

Ожидаемый вывод:
long expected = 0;

Пояснение

The starting rectangle is already a square.

Как подступиться

Сначала попробуйте сами, затем открывайте подсказки по одной.

Подсказка 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. Следуйте условию и ограничениям выше.

Лучшее принятое решение каждого участника. Более быстрые, экономные и высоко оценённые решения стоят выше.

# Участник Язык Время Память Оценка ИИ Решение
1 ННикита Python 954 ms - 4/5 Посмотреть код

Учитесь у других

Решения сообщества

Внимание, спойлер: ниже 1 полное решение Попробуйте сначала решить сами. Вы всегда можете посмотреть код других и AI-обзоры. Войдите и решите задание, чтобы присоединиться к обсуждению.