pku1816 Wild Words (trie)

a-z与?*的匹配,利用trie来实现的

 

#include <iostream> #include <vector> #include <algorithm> using namespace std; vector<int> res; const int kind=28;//字母种类 struct Treenode//树的结点结构 { vector<int> ids;//这个附加变量在本题中记录遍历到该结点形成的字符串出现的次数,在不同题中可记录不同的内容。 Treenode *next[kind];//指向儿子结点 Treenode()//每个结点的初始化 { for(int i=0;i<kind;i++) next[i]=NULL; } }; void insert(Treenode *&root,char *word, int id)//向以root为根结点的树中插入串word { Treenode *location=root; int i=0,branch=0; if(location==NULL) {location=new Treenode();root=location;} while(word[i]) { if (word[i] == '?') branch = 26; else if (word[i] == '*') branch = 27; else branch = word[i]-'a'; if(location->next[branch] == NULL) location->next[branch]=new Treenode();//如果不存在,建新结点 i++; location=location->next[branch]; } location->ids.push_back(id); } void search(Treenode* location, char* word) { int curid, branch, i; if (location == NULL) return; if (*word == 0) { if (location->next[27] != NULL) search(location->next[27], word); if (location->ids.size() > 0) { for (curid=0; curid<location->ids.size(); curid++) res.push_back(location->ids[curid]); } return; } branch = *word - 'a'; if (location->next[branch]!=NULL) search(location->next[branch], word+1); if (location->next[26] != NULL) search(location->next[26], word+1); if (location->next[27] != NULL) { for (i=0; i<=strlen(word); i++) search(location->next[27], word+i); } } int main() { int n, m, i, j; char str[40]; Treenode* root = NULL; vector<int>::iterator ii, iend; //freopen("data.txt", "r", stdin); cin >> n >> m; for (i=0; i<n; i++) { cin >> str; insert(root, str, i); } for (i=0; i<m; i++) { res.clear(); cin >> str; search(root, str); if (res.empty()) cout << "Not match"; else { sort(res.begin(), res.end()); iend = unique(res.begin(), res.end()); cout << res[0]; for (ii=res.begin(), ++ii; ii!=iend; ++ii) { cout << " " << *ii; } } cout << endl; } return 0; }

你可能感兴趣的:(pku1816 Wild Words (trie))