1

我有一个后缀树,这棵树的每个节点都是一个结构

struct state {
int len, link;
map<char,int> next; };
state[100000] st;

我需要为每个节点制作 dfs 并获取我可以到达的所有字符串,但我不知道如何制作。这是我的 dfs 函数

 void getNext(int node){
  for(map<char,int>::iterator it = st[node].next.begin();it != st[node].next.end();it++){
      getNext(it->second);
 }
}

如果我能做出类似的东西就完美了

map<int,vector<string> >

其中 int 是我的树的一个节点和我可以到达的向量字符串

现在它可以工作了

void createSuffices(int node){//, map<int, vector<string> > &suffices) {
if (suffices[sz - 1].size() == 0 && (node == sz - 1)) {
    // node is a leaf
    // add a vector for this node containing just 
    // one element: the empty string
    //suffices[node] = new vector<string>
    //suffices.add(node, new vector<string>({""}));
    vector<string> r;
    r.push_back(string());
    suffices[node] = r;
} else {
    // node is not a leaf
    // create the vector that will be built up
    vector<string> v;
    // loop over each child
    for(map<char,int>::iterator it = st[node].next.begin();it != st[node].next.end();it++){
        createSuffices(it->second);
        vector<string> t = suffices[it->second];
        for(int i = 0; i < t.size(); i ++){
            v.push_back(string(1,it->first) + t[i]);
        }
    }
    suffices[node] = v;
}
}
4

1 回答 1

0

您可以将map<int, vector<string>>与您的深度优先搜索一起传递。当递归调用从某个节点返回时n,您知道该节点的所有足够的东西都准备好了。我的C++技能太有限了,所以我就用伪代码来写吧:

void createSuffices(int node, map<int, vector<string>> suffices) {
    if (st[node].next.empty()) {
        // node is a leaf
        // add a vector for this node containing just 
        // one element: the empty string
        suffices.add(node, new vector<string>({""}));
    } else {
        // node is not a leaf
        // create the vector that will be built up
        vector<string> v;
        // loop over each child
        foreach pair<char, int> p in st[node].next {
            // handle the child
            createSuffices(p.second, suffices);

            // prepend the character to all suffices of the child
            foreach string suffix in suffices(p.second) {
                v.add(concatenate(p.first, suffix));
            }                
        }
        // add the created vector to the suffix map
        suffices.add(node, v);
    }
}
于 2013-10-07T09:17:50.400 回答