Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
还是字典树给力!#include <stdio.h> #include <malloc.h> #include <string.h> #define M 26 typedef struct Trie1 { struct Trie1 *next[M]; char val[10]; }Trie; Trie *root; void init() { int i; root=(Trie*)malloc(sizeof(Trie)); for(i=0;i<M;i++) root->next[i]=NULL; } void bulit(Trie *T,char str1[],char str2[]) { int i,id,length,j; Trie *p,*q; p=root; length=strlen(str2); for(i=0;i<length;i++) { id=str2[i]-'a'; if(p->next[id]==NULL) { q=(Trie*)malloc(sizeof(Trie)); for(j=0;j<M;j++) q->next[j]=NULL; p->next[id]=q; p=q; } else p=p->next[id]; } strcpy(p->val,str1); } void find(Trie *T,char str[]) { int i,id,length,flag=0; Trie *p=T; length=strlen(str); for(i=0;i<length;i++) { id=str[i]-'a'; if(p->next[id]==NULL) { flag=1; printf("eh\n"); return; } p=p->next[id]; } if(!flag) printf("%s\n",p->val); } void deal(Trie *T) { int i; if(T==NULL) return; for(i=0;i<M;i++) if(T->next[i]!=NULL) deal(T->next[i]); free(T); return; } int main() { char a[30],b[15],c[15]; init(); while(gets(a)&&a[0]!='\0') { sscanf(a,"%s%s",&b,&c); bulit(root,b,c); } while(gets(a)&&a[0]!='\0') find(root,a); deal(root); return 1; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator