【问题标题】:Filling an M x N rectangle with squares with sides of lengths 2^K, 2^(K - 1), ..., 4, 2, 1用边长为 2^K, 2^(K - 1), ..., 4, 2, 1 的正方形填充 M x N 矩形
【发布时间】:2014-11-22 21:27:06
【问题描述】:

给定一个 M x N 矩形,并要求用边长为 2^K, 2^(K - 1), ..., 4, 的正方形填充它2, 1。我们首先填充 2^K(尽可能多),然后填充 2^(K - 1),以此类推。我们总共需要多少个正方形?

我写了以下递归代码:

#include <stdio.h>
#include <stdlib.h>

long long_pow(long base, long exponent)
{
    if (!exponent)
        return 1L;

    return base * long_pow(base, exponent - 1L);
}

long cover(long width, long height, long side)
{
    if (width <= 0L || height <= 0L)
        return 0L;

    long full_width = width / side;   // The full width we can cover.
    long full_height = height / side; // The full height we can cover.

    return (full_width * full_height) // The full area we can cover
                                      // plus the rest (recursively).
           + cover(width - full_width * side, height, side / 2L)
           + cover(full_width * side, height - full_height * side, side / 2L);
}

int main()
{
    long width, height, k;
    scanf("%ld %ld %ld", &width, &height, &k);
    printf("%ld\n", cover(width, height, long_pow(2L, k)));
    return 0;
}

此代码在我收到的 10 个测试用例中的 1 个上失败。即,在123456789 987654321 4 上,它输出1690311532 而不是476300678536044。但是,在123456789 987654321 30 上,它会输出1437797319 的正确结果。其他测试用例也运行良好。

问题可能出在哪里?

【问题讨论】:

  • 我运行了它,它给了我123456789 987654321 4 测试用例的正确结果,即:476300678536044
  • @REACHUS:非常感谢。问题是long 在我的系统上不够长。用uint64_t 替换所有内容就可以了。

标签: c algorithm recursion


【解决方案1】:

代码的唯一问题是long 溢出。我改用unit64_t

【讨论】:

    猜你喜欢
    • 2022-11-13
    • 2023-03-08
    • 2012-12-27
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    相关资源
    最近更新 更多