我如何能得到杆尺寸在杆切割使用迭代

How i can get Rod sizes in Rod Cut using Recrsivly?

本文关键字:迭代 何能得      更新时间:2023-10-16

我想在棒材ct问题中获得最大收益的棒材尺寸。假设棒的长度是4。

1 = 5
2 = 4
3 = 3
4 = 10
在这种情况下

,最大收益将产生1,1,1,1,即20。我有最大的收入,但我怎么能得到杆尺寸代码如下:

#include<iostream>
using namespace std;
int Rod_Cut(int *,int);
int main()
{
    const int n=5;
    int arr[n]={0,5,4,3,10};
    int size[n]={0};

    cout<<Rod_Cut(arr,n)<<endl;

}
int Rod_Cut(int *arr, int n)
{
    if(n==0)
    {
        return 0;
    }
    int q=0;
    for(int i=1;i<n;i++)
    {
        q=max(q,arr[i]+Rod_Cut(arr,n-i));

    }
    return q;
}

有一种方法:

您需要返回每次计算中使用的序列。如果新值比目前的值更好,则必须保存新的"最佳"序列。最后返回找到的最佳序列。

这个建议不是最优的(例如性能),但也许它会给你一些想法。然后,您可以优化代码以获得更好的性能。

好运。

int Rod_Cut(int *,int, vector<int>&);
int main()
{
    const int n=5;
    int arr[n]={0,5,8,3,10};
    int size[n]={0};
    vector<int> v;  // Create vector for the best sequence
    cout<<Rod_Cut(arr,n,v)<<endl;
    // Print the best sequence
    for(auto e : v)
    {
        cout << e << " ";
    }

}
int Rod_Cut(int *arr, int n, vector<int>& v)
{
    if(n==0)
    {
        return 0;
    }
    int q=0;
    vector<int> t;        // Temp vector for next call
    vector<int> st;       // The best sequence found at this level
    for(int i=1;i<n;i++)
    {
        int temp = arr[i]+Rod_Cut(arr,n-i,t);
        if (temp > q)
        {
            // A new better sequence has been found
            st.clear();        // clear the former best sequence
            for(auto e : t)    // add the new best sequence
            {
                st.push_back(e);
            }
            st.push_back(i);   // add i used at this level
            q = temp;
        }
        t.clear();   // Prepare for next call
    }
    // Copy the best sequence to the returned vector
    for (auto e : st)
    {
        v.push_back(e);
    }
    return q;
}