Todos os desafios
Difícil 1 resolvido 100.0% de aceitação

Cut a Rectangle Into Squares

Find the fewest straight cuts needed to produce only squares.

O que você vai aprender

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

Problema

Ver tradução

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.

Restrições

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

Exemplos

Exemplo 1
Entrada:
height = 2
width = 3

Saída esperada:
expected = 2
Entrada:
long long height = 2;
long long width = 3;

Saída esperada:
long long expected = 2;
Entrada:
long height = 2;
long width = 3;

Saída esperada:
long expected = 2;

Explicação

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

Exemplo 2
Entrada:
height = 4
width = 4

Saída esperada:
expected = 0
Entrada:
long long height = 4;
long long width = 4;

Saída esperada:
long long expected = 0;
Entrada:
long height = 4;
long width = 4;

Saída esperada:
long expected = 0;

Explicação

The starting rectangle is already a square.

Como abordar

Tente sozinho primeiro e depois abra uma dica de cada vez.

Dica 1

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

Dica 2

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

Dica 3

Memoization or a table is helpful because many subrectangles repeat.

Complexidade esperada

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

Referências

Este desafio foi adaptado para o CodeUtility. Siga o enunciado e as restrições acima.

A melhor solução aprovada de cada programador. As mais rápidas, leves e mais bem avaliadas ficam no topo.

# Programador Linguagem Tempo Memória Avaliação da IA Solução
1 ННикита Python 954 ms - 4/5 Ver código

Aprenda com outros

Soluções da comunidade

Atenção: 1 solução completa abaixo Tente resolver sozinho primeiro. Você ainda pode espiar o código de outros desenvolvedores e as avaliações da IA. Entre e resolva o desafio para participar da discussão.