c++ - 以最少的正方形切割矩形

标签 c++ algorithm

我正在尝试解决以下问题:

A rectangular paper sheet of M*N is to be cut down into squares such that:

  1. The paper is cut along a line that is parallel to one of the sides of the paper.
  2. The paper is cut such that the resultant dimensions are always integers.

The process stops when the paper can't be cut any further.

What is the minimum number of paper pieces cut such that all are squares?

Limits: 1 <= N <= 100 and 1 <= M <= 100.

Example: Let N=1 and M=2, then answer is 2 as the minimum number of squares that can be cut is 2 (the paper is cut horizontally along the smaller side in the middle).

我的代码:

cin >> n >> m;

int N = min(n,m);
int M = max(n,m);
int ans = 0;

while (N != M) {
    ans++;
    int x = M - N;
    int y = N;
    M = max(x, y);
    N = min(x, y);
}

if (N == M && M != 0)
   ans++;

但我不明白这种方法有什么问题,因为它给了我一个错误的答案。

最佳答案

我认为 DP 和贪婪解决方案都不是最优的。以下是 DP 解决方案的反例:

考虑大小为 13 X 11 的矩形。DP 解决方案给出 8 作为答案。但最优解只有 6 个方格。

enter image description here

这个帖子有很多反例:https://mathoverflow.net/questions/116382/tiling-a-rectangle-with-the-smallest-number-of-squares

另外,看看这个以获得正确的解决方案:http://int-e.eu/~bf3/squares/

关于c++ - 以最少的正方形切割矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25903080/

相关文章:

c++ - 代码片段的时间复杂度是O(k*n^2)吗?

algorithm - 字母的最大可能矩形

c# - 计算给定 X Y 系列的局部最大值/最小值

java - 快速将字符串与 Java 中的集合进行比较

c++ - 如何优化这种组合算法?

c++ - 在 Qt Stickman 示例中将火柴人的头像更改为我教授的头像

c++ - OpenCV:如何使用 Haar Classifier Cascade 提高眼睛检测的准确性?

c++ - 二维 std::array 上的初始化列表

c++ - 为什么通过以下方式将ID传递给线程很不好?

algorithm - 寻找 n 位字符串的对手参数