1. 程式人生 > >trie樹 POJ 2503 Babelfish

trie樹 POJ 2503 Babelfish

Description

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
Hint

Huge input and output,scanf and printf are recommended.
第一次寫字典樹,之前做一個比較難的半天看不懂。。。找個簡單的先熟練一下

#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
const int maxnode=1000000+100;
int ch[maxnode][26];        //ch[i][j]儲存的是i節點的字元為j的子節點的位置
string val[maxnode];        //當前節點的值,中間節點統一為0或忽略
int
sz; int idx(char c) { return c-'a'; } void Insert(char *s1,string s2) { int u=0,n=strlen(s1); for(int i=0;i<n;i++) { int c=idx(s1[i]); if(!ch[u][c]) //如果u節點不存在值為c的子節點則新建一個 { memset(ch[sz],0,sizeof(ch[sz])); //val[sz]=0; ch[u][c]=sz++; } u=ch[u][c]; //得到子節點的位置 } val[u]=s2; } string find(string s) { int u=0,n=s.length(); for(int i=0;i<n;i++) { int c=idx(s[i]); if(ch[u][c]==0) return "eh"; u=ch[u][c]; } return val[u]; } int main() { char s[30],tmp1[15],tmp2[15]; sz=1; memset(ch[0],0,sizeof(ch[0])); while(gets(s)) { if(strcmp(s,"")==0) break; int len=strlen(s),flag=0; memset(tmp1,0,sizeof(tmp1)); memset(tmp2,0,sizeof(tmp2)); int i,j=0; for(i=0;i<len;i++) { if(s[i]==' ') { flag=1; j=0; continue; } if(flag==0) tmp1[j++]=s[i]; else tmp2[j++]=s[i]; } Insert(tmp2,string(tmp1)); } string temp; while(cin>>temp) cout<<find(temp)<<endl; return 0; }