hdu 1075 What Are You Talking About

http://acm.hdu.edu.cn/showproblem.php?pid=1075 字典树

View Code
 1 /*字典树,翻译*/
2 #include<iostream>
3 #include<cstring>
4 #include<cstdlib>
5 using namespace std;
6 struct node
7 {
8 node* child[26];
9 char word[12];
10 };
11 node*root=new node();
12 void init()//初始化
13 {
14 for(int i=0;i<26;i++) root->child[i]=NULL;
15 strcpy(root->word,"");
16 }
17 void insert(char* s1,char* s2)//有s2 推s1
18 {
19 int len=strlen(s2);
20 node* cur=root;
21 int i,pos,j;
22 for(i=0;i<len;i++)
23 {
24 pos=s2[i]-'a';
25 if(cur->child[pos]!=NULL) cur=cur->child[pos];
26 else
27 {
28 cur->child[pos]=new node();
29 node*temp=cur->child[pos];
30 for(j=0;j<26;j++) temp->child[j]=NULL,strcpy(cur->word,"");//单词置空
31 cur=temp;
32 }
33 }
34 strcpy(cur->word,s1);//s1放到对应的节点里面
35 }
36 void print(char* s)//找出s对应的英语单词
37 {
38 int len=strlen(s),i,j,pos;
39 node*cur=root;
40 for(i=0;i<len;i++)
41 {
42 pos=s[i]-'a';
43 if(cur->child[pos]!=NULL) cur=cur->child[pos];
44 else break;
45 }
46 if(i==len && strlen(cur->word)) printf("%s",cur->word);//find
47 else printf("%s",s);//not found , print itself
48 }
49 int main()
50 {
51
52 init();
53 char a[12],b[12],line[3008];
54 scanf("%s",&a);//读取start
55 getchar();
56 while(scanf("%s",&a)==1 && strcmp(a,"END"))//
57 {
58 scanf("%s",&b);
59 insert(a,b);
60 }
61 scanf("%s",&a);//读取start
62 getchar();//读回车
63 int i,len;
64 string temp;
65 while(gets(line) && strcmp(line,"END"))
66 {
67 //printf("line:%s\n",line);
68 temp="";
69 len=strlen(line);
70 for(i=0;i<len;i++)
71 {
72 if(isalpha(line[i])) temp+=line[i];
73 else
74 {
75 //printf("temp:%s\n",&temp[0]);
76 print(&temp[0]);//char*
77 temp="";
78 printf("%c",line[i]);
79 }
80 }
81 print(&temp[0]);
82 strcpy(line,"");//
83
84 print("\n");
85 //printf("................................\n");
86 }
87 system("pause");
88 return 0;
89 }


 

posted @ 2012-03-29 08:24  keepmoving89  阅读(228)  评论(0编辑  收藏  举报