C++功能的时间限制

C++ time limit for function

本文关键字:时间 功能 C++      更新时间:2023-10-16

>im 试图为我的 negamax alpha beta 算法实现时间限制,但我似乎无法弄清楚。 我试图实现的是: 开始计算移动,如果在 5 秒内未完成计算,则此时返回最佳移动。

我该怎么做?NEGAMAX甚至可能吗?

负极的伪代码:

01 function negamax(node, depth, α, β, color)
02     if depth = 0 or node is a terminal node
03         return color * the heuristic value of node
04     childNodes := GenerateMoves(node)
05     childNodes := OrderMoves(childNodes)
06     bestValue := −∞
07     foreach child in childNodes
08         v := −negamax(child, depth − 1, −β, −α, −color)
09         bestValue := max( bestValue, v )
10         α := max( α, v )
11         if α ≥ β
12             break
13     return bestValue

如果需要,我可以添加 negamax 算法的 C++ 实现

我能看到的唯一困难是递归,但这不是真正的问题,只需使用当前时间调用它,并在每次调用开始时检查经过的时间是否大于 5 秒:

01 function negamax(node, depth, α, β, color, startTime)
02     if (currentTime - startTime > 5sec) or depth = 0 or node is a terminal node
03         return color * the heuristic value of node

为方便起见,您可以使用包装器:

function negamaxWrap(node, depth, α, β, color)
    return negamax(node, depth, α, β, color, currentTime)

如何确保您获得最佳价值?当堆栈展开时,返回值仍将通过测试:

bestValue := max( bestValue, v )

因此,您将获得到目前为止找到的值的max