Problem Description
A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
You are to find all the hat’s words in a dictionary.
You are to find all the hat’s words in a dictionary.
Input
Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words.
Only one case.
Only one case.
Output
Your output should contain all the hat’s words, one per line, in alphabetical order.
Sample Input
a ahat hat hatword hziee word
Sample Output
ahat
hatword
题意:找出能有已知给定两个单词组成的单词。
解决方法:Tire树和map。
这里用的是Tire树。信息域标记最后一个字符。
Ps:可恶的寝室断网了,看来得长时间不能更新博客了~~
AC code:
#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
#define M 50005
#define N 60
char str[M][N];
char s1[N],s2[N];
struct node
{
int flag;
node *next[26];
};
void insert(node *root,char s[])
{
int i=0,j,k;
int len=strlen(s);
node *current=root;
while(i<len)
{
k=s[i]-'a';
if(current->next[k]==NULL)
{
node *p=new node;
for(j=0;j<26;++j)
p->next[j]=NULL;
p->flag=0;
if(i==len-1)
p->flag=1; //标记最后一个字符
current->next[k]=p;
current=p;
}
else
current=current->next[k];
++i;
}
}
bool search(node *root,char s[])
{
int i=0,j,k;
int len=strlen(s);
node *current=root;
while(i<len)
{
k=s[i]-'a';
if(current->next[k]==NULL)
return false;
current=current->next[k];
i++;
}
return current->flag;
}
int main()
{
int i,j,k,cnt=0,temp,m,n;
node *root=new node;
for(i=0;i<26;++i)
root->next[i]=NULL;
root->flag=0;
while(gets(str[cnt]))
{insert(root,str[cnt]); cnt++;}
for(i=0;i<cnt;++i)
{
temp=strlen(str[i]);
for(j=1;j<temp;++j)
{
memset(s1,0,sizeof(s1));
memset(s2,0,sizeof(s2));
for(m=0;m<j;++m)
s1[m]=str[i][m];
for(n=j;n<temp;++n)
s2[n-j]=str[i][n];
if(search(root,s1)&&search(root,s2))
{ cout<<str[i]<<endl; break;}
}
}
return 0;
}
本文详细介绍了如何使用 Tire 树和 map 数据结构来解决字典问题,找出所有能由两个给定单词组成的特殊单词,并提供了 AC 的代码实现。文章通过实例解释了解决方法,包括输入输出格式及示例数据解析。
533

被折叠的 条评论
为什么被折叠?



