我有一个后缀树,这棵树的每个节点都是一个struct
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 :(得分: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);
}
}