【发布时间】:2011-06-06 00:16:32
【问题描述】:
好的,这有点棘手。
我有一堆采用表达式树的代码:
((a + b)/(c + d) + sqrt(e))
以前缀形式存储在向量中(我使用的是 C++,但我只需要算法):
+(/(+(a,b),+(c,d)),sqrt(e)) //括号只是为了帮助你阅读。每个运算符和终端都是向量中的一个元素。
现在还有另一种表示表达式树的方法,称为 ORF 形式
(论文第三页:http://arxiv.org/ftp/cs/papers/0102/0102027.pdf)
在这种形式中,您可以像从左到右、从上到下阅读树一样表示树。
((a + b)/(c + d) + sqrt(e)) 现在变成:
+/sqrt++eabcd
我一直没有做的是创建一个可以转换的算法:
+/sqrt++eabcd //ORF
into:+(/(+(a,b),+(c,d)),sqrt(e)) //前缀
到目前为止,我只有一些代码来获取不同级别的树的宽度:
bool ConvertPrefixToORF(const std::vector<Node> & individual,
std::vector<Node> & ETindividual){
bool all_terminal = false;
int breadth;
int breadthOfDepth[individual.size()];
int depthCounter = 0;
breadthOfDepth[0] = 1;
//Resize only once.
ETindividual.reserve(individual.size());
while (all_terminal == false) {
//Reset breadth
breadth = 0;
//Iterate over next level and calculate depth of level after that.
for (int i = 0; i < breadthOfDepth[depthCounter]; i++) {
all_terminal = true;
//If the individual is a function...
if (individual[current+i].isFunction()) {
//Get individual from i'th item at this depth
function f = individual[current + i];
//Increment breadth of next level with arity
breadth += f->getArity();
//if a single function is found
all_terminal = false;
}
}
//Go down a level in the tree.
depthCounter++;
//Set the breadth of that tree depth:
breadthOfDepth[depthCounter] = breadth;
}
}
提前感谢您的帮助!这让我很头疼。哦,这对性能至关重要:(
【问题讨论】:
标签: c++ algorithm expression-trees prefix-tree