HDU-1247-Hats Words
http://acm.hdu.edu.cn/showproblem.php?pid=1247
还是字典树的题目,将每个单词分成两个单词即可,查找是否两个单词均在字典树中
注意建树的时和之前略有区别,这题在插入单词时,只需记录单词结尾的节点,不需要记录一个单词的所有前缀
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
char word[50005][20];
struct node
{
int count;
node *childs[26];
node()
{
count=0;
int i;
for(i=0;i<26;i++)
childs[i]=NULL;
}
};
node *root=new node;
node *current,*newnode;
void insert(char *str)
{
int i,m;
current=root;
for(i=0;i<strlen(str);i++)
{
m=str[i]-'a';
if(current->childs[m]!=NULL)
current=current->childs[m];
else
{
newnode=new node;
current->childs[m]=newnode;
current=newnode;
}
}
current->count=1;
}
int search(char *str) //在字典树中查找一个单词是否存在
{
int i,m;
current=root;
for(i=0;i<strlen(str);i++)
{
m=str[i]-'a';
if(current->childs[m]==NULL)
return 0;
current=current->childs[m];
}
return current->count;
}
int main()
{
int i,j,t=0,len;
char s1[20],s2[20];
while(scanf("%s",word[t])!=EOF)
{
insert(word[t]);
t++;
}
for(i=0;i<t;i++)
{
len=strlen(word[i]);
for(j=1;j<len;j++) //将单词分成两部分
{
strncpy(s1,word[i],j);
s1[j]='\0'; //刚开始忘了加这句,调试半天没输出。。
strncpy(s2,word[i]+j,len-j);
s2[len-j]='\0';
if(search(s1)&&search(s2))
{
printf("%s\n",word[i]);
break;
}
}
}
return 0;
}