题意:给出N(<=10000)个单词,单词长度小于等于20。在给出一个串T,要求按照字典序输出所有输入串中以T为前缀的串。注意同相同的串可能有多个。
题解:对N个串造一个Trie树,然后拿着T在树上跑,如果T串失败了,那么直接退出。T匹配到了某个Node,然后从这个Node开始DFS就可以了。
Code:
#include<bits/stdc++.h>
using namespace std;
const int MAX = 1000;
char buff[MAX],delta[MAX];
struct Trie_Node{
Trie_Node * nxt[26];
int exist;
};
Trie_Node * root;
Trie_Node * Trie_Create(){
Trie_Node * node =(Trie_Node*)(malloc(sizeof(Trie_Node)));
node->exist = false;
memset(node->nxt,0,sizeof(node->nxt));
return node;
}
void Trie_Insert(Trie_Node * root,char * word){
Trie_Node * node = root;
char * p = word;
while (*p){
int id = *p -'a';
if (node->nxt[id]==NULL){
node->nxt[id] = Trie_Create();
}
node = node->nxt[id];
p++;
}
node->exist++;
}
void Trie_Dfs(Trie_Node * node,int length){
for (int i=0;i<(node->exist);i++){
printf("%s",buff);
delta[length] ='\0';
printf("%s\n",delta);
}
for (int i=0;i<=25;i++){
if (node->nxt[i]!=NULL){
delta[length] = i+'a';
Trie_Dfs(node->nxt[i],length+1);
}
}
}
void Trie_Search(Trie_Node * root,char * word){
Trie_Node* node = root;
char * p = word;
while (*p){
int id = *p-'a';
node = node->nxt[id];
if (node==NULL){
return;
}
p++;
}
Trie_Dfs(node,0);
}
int main(){
root = Trie_Create();
int n;
scanf("%d\n",&n);
while (n--){
scanf("%s",buff);
Trie_Insert(root,buff);
}
scanf("%s",buff);
Trie_Search(root,buff);
return 0;
}