字典树的题是我一个月前做的了,到现在依然记得,他是我ac的第一个字典树题目。嘻嘻。
ac代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <string> #include <set> using namespace std; const int maxn=26; const int maxlen=100; char ss1[50005][maxlen],ss2[maxlen],ss3[maxlen]; struct node { bool flg; node *next[maxn]; node() { flg=false; for(int i=0;i<maxn;i++) next[i]=NULL; } ~node() { for(int i=0;i<maxn;i++) if(next[i]!=NULL) next[i]=NULL; } }; class Trie { public : node *root; Trie() { root=NULL; } void Insert(string str) { if(!root) root=new node(); node *location=root; for(int i=0;i<str.length();i++) { int num=str[i]-'a'; if(location->next[num]==NULL) location->next[num]=new node(); location=location->next[num]; } location->flg=true; } bool Search(string str) { node *location=root; for(int i=0;i<str.length();i++) { int num=str[i]-'a'; if(location->next[num]==NULL) return false; location=location->next[num]; } return location->flg; } }t; int main() { string str1,str2; int line=0; memset(ss1,' ',sizeof(ss1)); while(cin.getline(ss1[line],maxlen)) { str1=ss1[line++]; t.Insert(str1); } for(int i=0;i<line;i++) { for(int j=1;j<strlen(ss1[i]);j++) { str1=str2=""; memset(ss2,' ',sizeof(ss2)); memset(ss3,' ',sizeof(ss3)); strncpy(ss2,ss1[i],j); ss2[j]='\0'; strncpy(ss3,ss1[i]+j,strlen(ss1[i])-j); ss3[strlen(ss1[i])-j]='\0'; // cout<<ss2<<' '<<ss3<<endl; str1=ss2,str2=ss3; if(t.Search(str1)&&t.Search(str2)) { cout<<ss1[i]<<endl; // system("pause"); break; } } } return 0; }
欢迎批评指正。谢谢!