http://poj.org/problem?id=1035
View Code
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; struct node { char str[20]; int index; }ans[10010]; struct Trie { Trie *br[26]; int index; void init() { index=0; for(int i=0;i<26;++i) br[i]=NULL; } }*root,tree[150010]; int p; void build(char *s,int idx) { Trie *t=root; for(int i=0;s[i];++i) { int id=s[i]-'a'; if(!t->br[id]) { tree[++p].init(); t->br[id]=&tree[p]; } t=t->br[id]; } t->index=idx; } int search(char *s) { Trie *t=root; for(int i=0;s[i];++i) { int id=s[i]-'a'; if(!t->br[id]) return 0; t=t->br[id]; } return t->index; } void repla(char *from,char *to,int pos,char c) { //替代某个字符 strcpy(to,from); to[pos]=c; } void insert(char *from,char *to,int pos,char c) { //插入某个字符 int len=strlen(from); for(int i=0;i<pos;++i) to[i]=from[i]; to[pos]=c; for(int i=pos;i<len;++i) to[i+1]=from[i]; to[len+1]='\0'; } void delet(char *from,char *to,int pos) { //删除某个字符 int len=strlen(from); for(int i=0;i<pos;++i) to[i]=from[i]; for(int i=pos;i<len-1;++i) to[i]=from[i+1]; to[len-1]='\0'; } int cmp(const node &a,const node &b) { return a.index<b.index; } int main() { tree[0].init(); root=&tree[0]; char str[20],temp[20]; int idx=1; while(scanf("%s",str),str[0]!='#') { build(str,idx++); } while(scanf("%s",str),str[0]!='#') { if(search(str)) printf("%s is correct\n",str); else { int len=strlen(str); int x,cnt=0; for(int i=0;i<len;++i) { delet(str,temp,i); if((x=search(temp))!=0) { strcpy(ans[cnt].str,temp); ans[cnt++].index=x; } for(int j=0;j<26;++j) { repla(str,temp,i,j+'a'); if((x=search(temp))!=0) { strcpy(ans[cnt].str,temp); ans[cnt++].index=x; } insert(str,temp,i,j+'a'); if((x=search(temp))!=0) { strcpy(ans[cnt].str,temp); ans[cnt++].index=x; } } } for(int i=0;i<26;++i) { insert(str,temp,len,i+'a'); if((x=search(temp))!=0) { strcpy(ans[cnt].str,temp); ans[cnt++].index=x; } } sort(ans,ans+cnt,cmp); printf("%s:",str); if(cnt) printf(" %s",ans[0].str); for(int i=1;i<cnt;++i) if(ans[i].index!=ans[i-1].index) printf(" %s",ans[i].str); printf("\n") ; } } return 0; }