Pergunta

I have a suffix tree, each node of this tree is a struct

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

I need to make dfs for each node and get all strings which I can reach, but I don't know how to make. This is my dfs function

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

It will be perfect if I can make something like

map<int,vector<string> >

where int is a node of my tree and vector strings which I can reach

now it works

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;
}
}
Foi útil?

Solução

You can pass the map<int, vector<string>> together with your depth first search. When a recursive call returns from a certain node n, you know that all suffices from that node are ready. My C++ skills are too limited, so I'll write it in pseudo-code:

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);
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top