POJ 2503 Babelfish (词典)
这道题用的词典来解的,应该也可以用Trie树(但是我暂时不会):
词典就是一个键值Key,和一个对应的值Value
前往题目:POJ 2503
| Describe: |
| You have just moved from Waterloo to a big city. The people here speak an incomprehensible dialect of a foreign language. Fortunately, you have a dictionary to help you understand them. |
| Input: |
| Input consists of up to 100,000 dictionary entries, followed by a blank line, followed by a message of up to 100,000 words. Each dictionary entry is a line containing an English word, followed by a space and a foreign language word. No foreign word appears more than once in the dictionary. The message is a sequence of words in the foreign language, one word on each line. Each word in the input is a sequence of at most 10 lowercase letters. |
| Output: |
| Output is the message translated to English, one word per line. Foreign words not in the dictionary should be translated as "eh". |
| Sample Input: |
| dog ogday cat atcay pig igpay froot ootfray loops oopslay atcay ittenkay oopslay |
| Sample Output: |
| cat eh loops |
题目大意:
题意很好理解,就是给一堆英文单词和与之对应的火星文,然后给若干个火星文,如果词典里有对应的英文单词,则输出,否则输出“eh”。
解题思路:
构造一个词典即可,但是因为此题数据量较大,除了用printf和scanf以外,在查找的时候还需要用二分查找,将复杂度降到O(log n),不然会T吧。
AC代码:
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 #include <algorithm> 5 #define N 100000 // 最大词典数 6 using namespace std; 7 struct node 8 { 9 char w[100]; 10 char e[100]; 11 } s[N]; // 用结构体构造的词典,我想到的最简单的方法就是用结构体了,其他的更好的还没想到 12 bool cmp(struct node a, struct node b) // 排序的比较函数 13 { 14 return strcmp(a.w,b.w)>=0?1:0; // 注意这里,除0以外所有数都是true WA了一次 15 } 16 int main() 17 { 18 int i = 0; // 输入词典的计数器 19 int f = 1; // 判断能否找到的标志 20 char c,tmp[100]; // c是判断当前读入的是词典还是一个询问,tmp为中间字符串变量 21 while(~scanf("%s",s[i].e)) 22 { 23 c = getchar(); // 如果为换行,说明是个询问 24 if(c == '\n') 25 { 26 strcpy(tmp,s[i].e); // 不要忘了将字符串复制给tmp 27 break; 28 } 29 if(c == ' ') scanf("%s",s[i].w); // 如果是空格,说明是个词典 30 i++; 31 } 32 sort(s,s+i,cmp); // 词典按字典序降序排列 33 do 34 { 35 // 初始变量的各种初始化 36 f = 1; 37 int l = 0, r = i-1, mid,t; 38 mid = (r-l)/2+l; 39 t = strcmp(s[mid].w,tmp); 40 while(t != 0) 41 { 42 if(r-l == 1) // 这个 43 { 44 if(strcmp(s[l].w,tmp) == 0) mid = l; 45 else if(strcmp(s[r].w,tmp) == 0) mid = r; 46 else f = 0; 47 break; 48 } 49 if(r == l) // 还有这个,都是在临界点的特判 50 { 51 if(strcmp(s[r].w,tmp) != 0) 52 f = 0; 53 else mid = r; 54 break; 55 } 56 if(r < l) {f = 0; break;} // 有备无患,小的话直接break 57 if(t > 0) // 常规二分 58 { 59 l = mid; 60 mid = (r-l)/2+l; 61 } else { 62 r = mid; 63 mid = (r-l)/2+l; 64 } 65 t = strcmp(s[mid].w,tmp); 66 } 67 if(f) printf("%s\n",s[mid].e); // 按要求输出 68 else printf("eh\n"); 69 }while(~scanf("%s",tmp)); 70 return 0; 71 }
小结:
终于学会了词典,那个电话聊天狂人那道题应该也可以这么做吧,挺好的方法。
更新:
灵光一闪,弄两个数组,一个词典数组,词典数组里面存地址,地址对应就是火星文那个数组,应该也可以。

浙公网安备 33010602011771号