标签:
#include<iostream> #include<string> #define kind 30 using namespace std; class trie { private: struct trienode { trienode * next[kind]; char c[kind]; int branch; trienode() { branch=0; int i; for(i=0;i<kind;i++) next[i]=NULL; for(i = 0; i < kind; ++ i) c[i] = ‘ ‘; } }; trienode * root; public: trie() { root=NULL; } void insert(char s[],char s1[]) { trienode * location = root; if(location == NULL) location = root = new trienode(); int i = 0,k; while(s[i]) { k=s[i]-‘a‘; if(location->next[k]) location->next[k]->branch++; else { location->next[k]=new trienode(); location->next[k]->branch++; } i++; location = location->next[k]; } memcpy(location->c,s1,strlen(s1)); //cout<<location->c<<endl;//<<" 插入"<<endl; } int search(char s[]) { trienode * location = root; if(!location) return 0; int k,i = 0,ans; while(s[i]) { k=s[i] - ‘a‘; if(!location->next[k]) return 0; ans = location->next[k]->branch; location = location->next[k]; i++; } if(location) { for(i = 0;location->c[i] != ‘ ‘; ++ i) cout<<location->c[i]; cout<<endl; } return ans; } }; int main() { //freopen("acm.acm","r",stdin); char b[11]; char c[11]; char k; int i = 0; int j; string u; int num; trie mytrie; while(cin>>b,k = getchar(),cin>>c) { //k = getchar(); // cout<<b<<" "<<c<<endl; if(k != ‘ ‘) break; mytrie.insert(c,b); ++ i; } // cout<<"-----------"<<endl; if(!mytrie.search(b)) cout<<"eh"<<endl; if(!mytrie.search(c)) cout<<"eh"<<endl; while(cin>>b) { // cout<<b<<endl; if(!mytrie.search(b)) cout<<"eh"<<endl; } return 0; }
标签:
原文地址:http://www.cnblogs.com/gavinsp/p/4568455.html