【发布时间】:2016-01-22 20:49:48
【问题描述】:
我必须估计 Solve() 的时间复杂度:
// Those methods and list<Element> Elements belongs to Solver class
void Solver::Solve()
{
while(List is not empty)
Recursive();
}
void Solver::Recursive(some parameters)
{
Element WhatCanISolve = WhatCanISolve(some parameters); //O(n) in List size. When called directly from Solve() - will always return valid element. When called by recursion - it may or may not return element
if(WhatCanISolve == null)
return;
//We reduce GLOBAL problem size by one.
List.remove(Element); //This is list, and Element is pointed by iterator, so O(1)
//Some simple O(1) operations
//Now we call recursive function twice.
Recursive(some other parameters 1);
Recursive(some other parameters 2);
}
//This function performs search with given parameters
Element Solver::WhatCanISolve(some parameters)
{
//Iterates through whole List, so O(n) in List size
//Returns first element matching parameters
//Returns single Element or null
}
我的第一个想法是它应该在 O(n^2) 左右。
然后我想到了
T(n) = n + 2T(n-1)
其中(根据 wolframalpha)扩展为:
O(2^n)
但是我认为第二个想法是错误的,因为 n 在递归调用之间减少了。
我还对大型集进行了一些基准测试。结果如下:
N t(N) in ms
10000 480
20000 1884
30000 4500
40000 8870
50000 15000
60000 27000
70000 44000
80000 81285
90000 128000
100000 204380
150000 754390
【问题讨论】:
-
这是什么语言?当然不是 C++。
-
很多时候,当你在给定时间内减少购买一定数量的成本时,你最终会得到某种形式的 log(n)
-
知道
WhatCanISolve的工作原理很难估计。 IE。什么时候可以返回 null(w.r.t. 列表大小)。 -
@SergeyA 这是伪c++,我简化了很多,使其更简洁。
-
@MikhailMaltsev 此函数迭代元素 (std::list
)。在每次迭代中,它比较 6 个双精度数。
标签: c++ algorithm recursion time-complexity