POJ - 2503

POJ - 2503

 

这题用map做时有2100ms,而用字典树去做时360ms就过了。

map的

字典树的:

下面是代码:

 1 #include<iostream>
 2 #include <stdio.h>
 3 #include <map>
 4 using namespace std;
 5 int main()
 6 {
 7     char str[50],h[50];
 8     string tp;
 9     int count=1;
10     map<string,string>dic;
11     while(true){
12         char c;
13         if((c=getchar())=='\n')break;
14         else
15         {
16           str[0]=c;
17           int i=1;
18           while(true)
19           {
20             c=getchar();
21             if(c==' ')
22             {
23                 str[i]='\0';
24                 break;
25             }
26             else str[i++]=c;
27         }
28     }
29     scanf("%s",h);
30     getchar();
31     dic[h]=str;
32     count++;
33 }
34     string tar;
35     while(cin>>tar)
36     {
37         map<string,string>::iterator p=dic.find(tar);
38         if(p==dic.end())
39            printf("%s\n","eh");
40         else cout << (*p).second << endl;
41     }
42     return 0;
43 }

 

 

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <string.h>
 5 using namespace std;
 6 char str[50],str1[50];
 7 
 8 struct Nod{
 9     char str[50];
10     Nod*next[26];
11     Nod(){
12         for(int i = 0; i < 26; i ++){
13             next[i] = NULL;
14         }
15     }
16 }t;
17 
18 void mkTrie(char *s, char *ss){
19     Nod *p = &t;
20     for(int i = 0; ss[i]; i ++){
21         int a = ss[i] - 'a';
22         if(p->next[a]==NULL){
23             p->next[a] = new Nod;
24         }
25         p = p->next[a];
26     }
27     strcpy(p->str,s);
28 }
29 
30 void find(char *s){
31     Nod *p = &t;
32     for(int i = 0; s[i]; i ++){
33         int a = s[i]-'a';
34         if(p->next[a] ==NULL){
35             puts("eh");
36             return;
37         }
38         p = p->next[a];
39     }
40     puts(p->str);
41 }
42 int main(){
43     char c;
44     while(1){
45         if((c=getchar())=='\n')break;
46         str[0] = c;
47         int i = 1;
48         while(1){
49             if((c=getchar())==' ')break;
50             str[i++] = c;
51         }
52         str[i] = '\0';
53         i = 0;
54         while(1){
55             if((c=getchar())=='\n')break;
56             str1[i++] = c;
57         }
58         str1[i] = '\0';
59         mkTrie(str,str1);
60     }
61     while(scanf("%s",str)!=EOF){
62         find(str);
63     }
64     return 0;
65 }

 

posted @ 2017-07-06 08:22  starry_sky  阅读(127)  评论(0编辑  收藏  举报