2013-10-07 191 views
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; 
} 
} 
+0

为什么要使用地图,你想这对每个节点所以只要矢量指针的载体。无论哪种方式,你都会有相当多的冗余。 – Leeor

+0

我认为检查一片叶子是错误的。如果一个节点没有子节点,那么它就是一个叶子,也就是说,如果'next'是一个空映射。我不知道上面的代码片段中有什么'sz',但它看起来不正确。 –

回答

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); 
    } 
} 
+0

因为我可以看到有一些问题,每次都有足够的空间 –

+0

如果我们想要改变足够的话,我们是否需要通过参考而不是val:map >并且足够' – doctorlove

+0

@doctorlove是的,绝对。我试图把它写成C++ ish(带有引用),但是我被卡住了,所以我决定把它写得尽可能简单......但的确,map *必须*通过引用传递,否则这会赢得'工作。 –