您的位置:首页 > 其它

杭电hdu 1247 hat's words

2012-03-28 12:23 274 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1247

字典树的又一简单题,简单介绍见本目录中的另一个题。

//字典树的应用问题
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 51

char words[50001][MAX];//缓存所有输入的单词

typedef struct _node
{
bool end;
_node * next[26];
}node;

static node root = {0, {NULL}};

void insert(char * word, int len)//向字典树中插入数据
{
node *cur, *newnode;
int i;
cur = &root;
for(i = 0; i < len; ++ i){
if(cur->next[word[i]-'a'] == NULL){
newnode = (node*)malloc(sizeof(node));
memset(newnode, 0, sizeof(node));
cur->next[word[i]-'a'] = newnode;
}
cur = cur->next[word[i]-'a'];
}
cur->end = true;
}

bool find(char * word, int len)//查找字典树
{
node *cur = &root;
int i;
for(i = 0; i < len; ++ i){
if(cur->next[word[i]-'a'] == NULL)return false;
cur = cur->next[word[i]-'a'];
}
if(!cur->end)return false;
return true;
}

int main()
{
//	freopen("input.txt","r", stdin);
char left[MAX], right[MAX];
int cnt = 0, i, j;
while(scanf("%s", words[cnt])!=EOF){
insert(words[cnt ++], strlen(words[cnt]));//为什么cnt++不能放在后面呢?
}

for(i = 0; i < cnt; ++ i){
int len = strlen(words[i]);
for(j = 1; j < len; ++ j){
strcpy(left, words[i]);
left[j] = '\0';
strcpy(right, words[i]+j);
if(find(left, j) && find(right, len-j)){
printf("%s\n", words[i]);
break;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: