【问题标题】:Price mismatch in recursive top-down implementation of rod cutting problem切杆问题递归自顶向下实现中的价格不匹配
【发布时间】:2020-09-03 23:04:10
【问题描述】:

我正在学习如何解决切割棒的最大利润问题。但是当我编写这段代码时,它并没有产生什么剧烈的结果。他给出的结果是 20,但正确的结果是 10。

代码如下:

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

int _max(int a, int b) { if (a > b) return a; else return b; }

int cut_rod(int prices[], int size)
{
    if (size == 0) return size;

    int max = 0;
    for (int i = 1; i <= size; i++)
    {
        max = _max(max, prices[i] + cut_rod(prices, size - i));
    }

    return max;
}

int main(int argc, char** argv)
{
    int arr[] = { 1,5,8,9};
    int size = sizeof(arr) / sizeof(arr[0]);

    int max = cut_rod(arr, size);
    printf("Maximum Obtainable Value is %d", max);
    getchar();
    return 0;
}

这段代码有什么问题?

【问题讨论】:

    标签: c dynamic-programming


    【解决方案1】:
    for (int i = 0; i < size; i++)
    {
        max = _max(max, prices[i] + cut_rod(prices, size - i - 1));
    }
    

    这是你的错误:cut_rod(prices, size - i - 1))for (int i = 0; i &lt; size; i++)

    这是一个算法规则。 请仔细阅读算法说明。

    您从 arr[1] = prices[1] = 5(your values) 开始,但在描述算法中

    我们应该从 arr[0] = prices[0] = 1(your values) 开始

    为了更好地理解,你可以拿纸解析这段代码(递归)

    for (int i = 0; i < size; i++)
    {
        max = _max(max, prices[i] + cut_rod(prices, size - i - 1));
    }
    

    【讨论】:

      【解决方案2】:

      你访问 arr[]/prices[] 数组越界

      for (int i = 1; i <= size; i++)
      {
          max = _max(max, prices[i] + cut_rod(prices, size - i));
      }
      

      因为数组索引在 C 中从 0 开始计数。大小为 4,但没有 arr[4]

      【讨论】:

      • 我能用它做什么?
      • @maylor 我没有看过算法,所以一个疯狂的猜测:使循环条件 i &lt; size 而不是
      • 这怎么可能?
      猜你喜欢
      • 2017-09-13
      • 2017-10-29
      • 2011-07-27
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 2022-01-18
      • 1970-01-01
      相关资源
      最近更新 更多