您的位置:首页 > 理论基础 > 数据结构算法

poj2503Babelfish(Trie tree 或者map)

2013-05-17 20:30 183 查看
->题目还是戳这里<-

题目大意:还是给你一个字典,翻译单词。

题目分析:题目蛮简单,字典树练手题。不过STL可以水过。输入有点小刁难,需要小心点,其他的就没什么了。

详情请见代码:

#include <iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<map>
using namespace std;
const int N = 1000005;

map<string,string> lcm;
char explan[20],s[20];

int input()
{
int i = 0;
int flag = 0;
char c;
while(c = getchar())
{
if(c == '\n')
{
if(i == 0)
return 0;
else
{
s[i] = '\0';
return 1;
}
}
else
{
if(c == ' ')
{
explan[i] = '\0';
i = 0;
flag = 1;
}
else
{
if(flag)
s[i ++] = c;
else
explan[i ++] = c;
}
}
}
}

int main()
{
while(input())
{
lcm[s] = explan;
}
while(scanf("%s",s) != EOF)
{
map<string,string>::iterator it = lcm.find(s);
if(it != lcm.end())
cout<<lcm[s]<<endl;//printf("%s\n",lcm[s]);
else
printf("eh\n");
}
return 0;
}
//9632K	1157MS

/*
typedef struct node
{
struct node * next[26];
char s[101];
int end;
}tree;
char s[101];
char explan[101];

int input()
{
int i = 0;
int flag = 0;
char c;
while(c = getchar())
{
if(c == '\n')
{
if(i == 0)
return 0;
else
{
s[i] = '\0';
return 1;
}
}
else
{
if(c == ' ')
{
explan[i] = '\0';
i = 0;
flag = 1;
}
else
{
if(flag)
s[i ++] = c;
else
explan[i ++] = c;
}
}
}
}

void init(tree *t)
{
memset(t->s,0,sizeof(t->s));
for(int i = 0;i < 26;i ++)
t->next[i] = NULL;
t->end = 0;
}

void build(tree *t,int id)
{
if(t->next[s[id] - 'a'] == NULL)
{
t->next[s[id] - 'a'] = (tree *)malloc(sizeof(tree));
init(t->next[s[id] - 'a']);
}
if(s[id + 1] == '\0')
{
strcpy(t->next[s[id] - 'a']->s,explan);
t->next[s[id] - 'a']->end = 1;
return;
}
else
{
build(t->next[s[id] - 'a'],id + 1);
}
}

void query(tree *t,int id)
{
if(s[id] != '\0' && t->next[s[id] - 'a'] == NULL)
{
printf("eh\n");
return;
}
if(s[id] == '\0')
{
if(t->end == 1)
{
//printf("%s\n",t->s);
int i = 0;
while(t->s[i])
{
putchar(t->s[i]);
i ++;
}
putchar('\n');
return;
}
else
{
printf("eh\n");
return;
}
}
else
query(t->next[s[id] - 'a'],id + 1);
}

void print(tree *t)
{
for(int i = 0;i < 26;i ++)
{
if(t->next[i] != NULL)
print(t->next[i]);
}
if(t->end)
{
printf("%s\n",t->s);
return;
}
}

int main()
{
tree *root = NULL;
root = (tree *)malloc(sizeof(tree));
init(root);
while(input())
{
build(root,0);
//printf("%s %s\n",explan,s);
}
//print(root);
//system("pause");
while(scanf("%s",s) != EOF)
{
s[strlen(s)] = '\0';
query(root,0);
}
return 0;
}*/
//27976K	735MS
/*
dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay
s ab
sb abs
sba absd

atcay
ittenkay
oopslay
a
ab
abs
absd
absda

ab sb
aba sba

s
sb
sba
*/


交了2份代码,效率差别很大,如果静态字典树,效率会更高。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 字典树