我如何能得到杆尺寸在杆切割使用迭代
How i can get Rod sizes in Rod Cut using Recrsivly?
我想在棒材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;
}
相关文章:
- 在C++中释放内存期间,迭代器与指针有何不同
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- 是什么导致我的循环在第一次迭代中运行得更慢
- 矢量迭代器不能与 std::shared_ptr<> 取消引用
- std::remove() 按预期处理文字,但不能与取消引用的迭代器一起工作
- 成员函数不能为集合迭代器和const_iterator的输入重载(但可以为其他 STL 迭代器重载)
- 插入 boost::multi_index 后迭代器变得无效?
- C++不能取消引用结束列表迭代器
- 为什么我不能在 c++ 中"map"的迭代器中使用"+1"?
- 你能pop_back一个向量,并且仍然使用迭代器到最后一个元素吗?
- 使用 std::vector<Particle> 粒子;函数 .at() 不能与迭代器一起使用,它作为 for 循环中的参数
- 为什么迭代 std::array 比迭代 std::vector 快得多?
- C 迭代器比索引慢得多
- 为什么使用预留分配存储后不能迭代和打印矢量的内容?
- 为什么我不能将迭代器应用于接受 const_iterator 引用的函数?
- 为什么它不能在 c++ 中获取迭代器作为引用
- 为什么我不能递增 std::unordered_map 迭代器?
- 为什么 ifstream::read 比使用迭代器快得多
- 为什么STL算法使用指针比std::向量迭代器快得多
- 如何使迭代器在迭代时表现得像一个类型