POJ 2503 字典树
题目链接:http://poj.org/problem?id=2503
题意:给定一个词典,输入格式为[string1' 'string2] 意思是string2的值为string1。 然后给定一波字符串问你该字符串在字典的值是多少?
思路:字典树模板题。 叶子结点存放的是对应词典中的值。
#include<iostream> #include<algorithm> #include<cstring> #include<string> #include<cstdio> #include<vector> #include<cmath> #include<time.h> #include<sstream> #include<map> using namespace std; const int MAXN=300000+5; const int MAXL=10+5; char str[MAXL],val[MAXL],ch[MAXL]; struct trie{ char val[MAXL]; int child[26]; trie(){ memset(child,0,sizeof(child)); } }Trie[MAXN]; int TrieN; void Insert(char *str,char *Val){ int x=0,len=strlen(str); for(int i=0;i<len;i++){ int d=str[i]-'a'; if(Trie[x].child[d]==0){ Trie[++TrieN]=trie(); Trie[x].child[d]=TrieN; } x=Trie[x].child[d]; } strcpy(Trie[x].val,Val); } void Search(char *str,char *ans){ int x=0,len=strlen(str); for(int i=0;i<len;i++){ int d=str[i]-'a'; if(Trie[x].child[d]==0){ strcpy(ans,"eh"); return; } x=Trie[x].child[d]; } strcpy(ans,Trie[x].val); } int main(){ #ifdef kirito freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); #endif int start=clock(); TrieN=0; while(gets(ch)&&ch[0]){ int lenc=strlen(ch),lens=0,lenv=0; bool flag=false; for(int i=0;i<lenc;i++){ if(ch[i]==' '){flag=true;continue;} if(!flag){ val[lenv++]=ch[i]; } else{ str[lens++]=ch[i]; } } val[lenv]='\0'; str[lens]='\0'; Insert(str,val); } while (~scanf("%s",str)){ if(!str[0]){break;} Search(str,val); printf("%s\n",val); } #ifdef LOCAL_TIME cout << "[Finished in " << clock() - start << " ms]" << endl; #endif return 0; }