您的位置:首页 > 其它

HDU1075——What Are You Talking About

2015-04-23 18:56 417 查看
字典树模板套用,最后一个字母里存放对应的原字符串。

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <algorithm>
using namespace std;
const int MAX=26;
char s[3005];
char english[15];
char martain[15];
typedef struct TrieNode
{
char final[15];
int fsign;
struct TrieNode *next[MAX]; //该节点的后续节点
} TrieNode;

TrieNode Memory[1000000]; //先分配好内存。 malloc 较为费时
int allocp = 0;

//初始化一个节点。nCount计数为1, next都为null
TrieNode * createTrieNode()
{
TrieNode * tmp = &Memory[allocp++];
tmp->fsign = 0;
for (int i = 0; i < MAX; i++)
tmp->next[i] = NULL;
return tmp;
}

void insertTrie(TrieNode * * pRoot, char * str,char *x)
{
TrieNode * tmp = *pRoot;
int i = 0, k;
//一个一个的插入字符
while (str[i])
{
k = str[i] - 'a'; //当前字符 应该插入的位置
if (tmp->next[k])
{

}
else
{
tmp->next[k] = createTrieNode();
}

tmp = tmp->next[k];
i++;
}
strcpy(tmp->final,x);
tmp->fsign=1;

}

int searchTrie(TrieNode * root, char * str)
{
if (root == NULL)
return 0;
if(str[0]=='\0')
return 0;
TrieNode * tmp = root;
int i = 0, k;
while (str[i])
{
k = str[i] - 'a';
if (tmp->next[k])
{
tmp = tmp->next[k];
}
else
return 0;
i++;
}
if(tmp->fsign==1)
{
printf("%s",tmp->final);
return 1;
}
else
return 0;
}

int main(void)
{

allocp=0;
TrieNode *Root = createTrieNode();
gets(s);
int length;
int i,j;
while(scanf("%s",english)!=EOF)
{
if(english[0]=='E')
break;

scanf("%s",martain);
insertTrie(&Root,martain,english);
}
getchar();
gets(s);
while(gets(s))
{
if(s[0]=='E')
return 0;
length=strlen(s);
j=0;
for(i=0;i<length;i++)
{
if(islower(s[i]))
{
english[j++]=s[i];
english[j]='\0';
}
else
{
if(!searchTrie(Root,english))
{
printf("%s",english);

}
printf("%c",s[i]);

j=0;
english[j]='\0';
}

}
printf("\n");
/*if(searchTrie(Root,s))
;
else
{
printf("%s",s);
}*/

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: