您的位置:首页 > 其它

hdu1247Hat’s Words(字典树---判断单词有无组合现象)

2013-08-07 16:56 309 查看
1.题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1247

 

2.参考代码:

 

#include <cstdio>
#include <cstring>

struct node{
int flag;   ///标记是否到达树的尾部
node* next[26];
node(){
flag=0;
memset(next,0,sizeof(next));
}
};

node* root=NULL;

void build(char* s){   ///建树
node* p=root;
int len=strlen(s);
for(int i=0;i<len;i++)
{
if(!p->next[s[i]-'a'])
p->next[s[i]-'a']=new node;
p=p->next[s[i]-'a'];
}
p->flag=1;   ///标记已到达单词尾部
}

int find(char* s){   ///查找
node* p=root;
int len=strlen(s);
for(int i=0;i<len;i++)
{
if(!p->next[s[i]-'a'])
return 0;
p=p->next[s[i]-'a'];
}
if(p->flag)   ///判断是否已经到达最后一个字母,避免只有前部分的相同
return 1;
else
return 0;
}

void Delete(node* p){
for(int i=0;i<10;i++)

{
if(!p->next[i])
Delete(p->next[i]);
}
delete p;
}

int main()
{
root=new node;
int i,j,k,c=0;
char str[50001][20];
//	while(gets(str[c]))   ///不能用gets()接收
while(~scanf("%s",str[c]))
{
build(str[c]);
c++;
}
for(i=0;i<c;i++)
{
int len=strlen(str[i]);
int count=0,x,y;
char a[20],b[20];
for(j=0;j<len;j++)   ///将字符串分段检索
{
count++;   ///计算单词个数
x=0;
y=0;   ///x和y是计算拆分后2个单词的个数
for(k=0;k<len;k++)
{
if(k<count)
a[x++]=str[i][k];
else
b[y++]=str[i][k];
}
a[x]='\0';   ///单词最后的'\0'别忘了
b[y]='\0';
if(find(a) && find(b))
{
printf("%s\n",str[i]);
break;
}
}
}
Delete(root);
return 0;
}


 

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