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=+;
const int MAXL=+;
char str[MAXL],val[MAXL],ch[MAXL];
struct trie{
char val[MAXL];
int child[];
trie(){
memset(child,,sizeof(child));
}
}Trie[MAXN];
int TrieN;
void Insert(char *str,char *Val){
int x=,len=strlen(str);
for(int i=;i<len;i++){
int d=str[i]-'a';
if(Trie[x].child[d]==){
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=,len=strlen(str);
for(int i=;i<len;i++){
int d=str[i]-'a';
if(Trie[x].child[d]==){
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=;
while(gets(ch)&&ch[]){
int lenc=strlen(ch),lens=,lenv=;
bool flag=false;
for(int i=;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[]){break;}
Search(str,val);
printf("%s\n",val);
}
#ifdef LOCAL_TIME
cout << "[Finished in " << clock() - start << " ms]" << endl;
#endif
return ;
}
上一篇:POJ 2001 字典树(入门题)


下一篇:input file上传文件扩展名限制