1. 程式人生 > >hdu1075(字典樹)

hdu1075(字典樹)

pid 換行 現在 img trie 單詞 word pen 字典

What Are You Talking About

題意:

  給出Martian的語言的單詞對應的英語單詞以及一段用Martian的語言寫成的文本,現在要求把文本翻譯成英文,文本中的空格,換行,‘\t’以及標點符號不用翻譯,如果某個單詞沒給出對應的英語單詞,那麽它也不用翻譯。

分析:

  用給出的Martian單詞建立,在單詞結尾對應的節點存下對應的英語單詞,註意一定要開一個標記代表這裏是單詞的結尾,因為可能存在一個單詞是另一個單詞前綴的情況,在這裏RE了很多次(代碼結束給出了我RE的數據)。

代碼:

技術分享圖片
#include <map>
#include <queue>
#include 
<math.h> #include <string> #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> using namespace std; #define ll long long #define ull unsigned long long #define cls(x) memset(x,0,sizeof(x)) #define clslow(x) memset(x,-1,sizeof(x)) const
int maxn=1e4; const int wordLen=30; char line[maxn]; struct TrieNode { char* s; bool isword; TrieNode* nex[26]; }; TrieNode* root; TrieNode* build() { TrieNode* node=new TrieNode; node->isword=false; cls(node->nex); return node; } void Insert(char* s,char* code) {
int len=strlen(s); TrieNode* node=root; for(int i=0;i<len;i++){ int x=s[i]-a; if(node->nex[x]==NULL){ node->nex[x]=build(); } node=node->nex[x]; } node->isword=true; node->s=new char[strlen(code)]; strcpy(node->s,code); } char* decode(char* s) { int len=strlen(s); TrieNode* node=root; for(int i=0;i<len;i++){ int x=s[i]-a; if(node->nex[x]==NULL){ return s; } node=node->nex[x]; } if(node->isword) return node->s; return s; } void del(TrieNode* node) { for(int i=0;i<26;i++){ if(node->nex[i]!=NULL){ del(node->nex[i]); } } free(node); } int main() { // freopen("in.txt","r",stdin); root=build(); char s1[wordLen],s2[wordLen]; while(scanf("%s",s1)!=EOF) { if(strcmp(s1,"START")==0) continue; else if(strcmp(s1,"END")==0) break; scanf("%s",s2); Insert(s2,s1); } getchar(); char word[wordLen]; while(gets(line)) { if(strcmp(line,"START")==0) continue; else if(strcmp(line,"END")==0) break; int cnt=0,len=strlen(line); for(int i=0;i<len;i++){ if(a<=line[i]&&line[i]<=z){ word[cnt++]=line[i]; word[cnt]=\0; } else{ if(cnt) printf("%s",decode(word)); printf("%c",line[i]); cnt=0; } } if(cnt) printf("%s",decode(word)); printf("\n"); } return 0; } /** START from fiwo hello difh trap dif mars riwosf earth fnnvk like fiiwj END START difh, i‘m fiwo riwosf. i fiiwj fnnvk! dif fnn f END **/
View Code

hdu1075(字典樹)