您的位置:首页 > 其它

HDU - 1075 What Are You Talking About(字典树)

2017-08-02 17:05 246 查看
点我看题

题意:给你一个英文火星文对应字典,让把火星文翻译为英文.

分析:用一棵字典树把字典建立起来,然后查询.

参考代码:

#include<cstdio>
#include<cmath>
#include<cstring>
#include<cctype>//islower(char ch)的头文件
#include<algorithm>
#include<iostream>

using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
const int maxn = 1e6+10;//树的结点,不要开太小
const int maxm = 3e3+10;//字符个数
//TireNode
int tn[maxn][26];//结点
int node;//结点个数
char w[maxn][12];//结点i代表的字符串
bool exist[maxn];//判断到当前为止是否存在从根到这里表示的火星文
char sen[maxm];//输入的**

//初始化,很重要
void init()
{
mem(tn[0],0);
node = 1;
mem(exist,false);
}

//单词插入
void TireInsert( char e[], char m[])
{
int p = 0;//火星文的下标
int root = 0;//对应树的根
int id;//字符的数字值
while( m[p] != '\0')
{
id = m[p]-'a';
if( tn[root][id] == 0)//不存在子树,新建一个结点
{
mem(tn[node],0);//结点初始化
tn[root][id] = node;
node++;//节点数加1
}
root = tn[root][id];//往下走
p++;
}
strcpy(w[root],e);//把翻译值存下来
exist[root] = true;//有
}

//单词查找
void TireSearch( char m[])
{
int p = 0;
int root = 0;
int id;
while( m[p] != '\0')
{
id = m[p]-'a';
if( tn[root][id] == 0)
{
printf("%s",m);
return;
}
root = tn[root][id];
p++;
}
if( exist[root])//存在
printf("%s",w[root]);
else//不存在
printf("%s",m);
}

int main()
{
init();
char word[25];
while( fgets(word,25,stdin) && strcmp(word,"START\n"))
;
while( fgets(word,25,stdin) && strcmp(word,"END\n"))
{
char a[15],b[15];
int len = strlen(word);
int flag = 0;
int p = 0;
for( int i = 0; i < len; i++)//把word分成英文火星文两个串
{
if( word[i] == ' ')
{
a[p] = '\0';
flag = 1;
p = 0;
continue;
}
if( islower(word[i]))
{
if( !flag)
a[p++] = word[i];
else
b[p++] = word[i];
}
}
b[p] = '\0';
// printf("%d %s\n",(int)strlen(a),a);
// printf("%d %s\n",(int)strlen(b),b);
TireInsert(a,b);
}

while( fgets(sen,maxm,stdin) && strcmp(sen,"START\n"))
;
while( fgets(sen,maxm,stdin) && strcmp(sen,"END\n"))
{
int len = strlen(sen);
char a[15];
int p = 0;
for( int i = 0; i < len; i++)
{
if( islower(sen[i]))
a[p++] = sen[i];
else
{
a[p] = '\0';
if( strcmp(a,""))
TireSearch(a);
printf("%c",sen[i]);
p = 0;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: