您的位置:首页 > 其它

hdu 1247 Hat’s Words trie 简单字典树

2012-08-13 20:35 513 查看
这道题我用得静态树,发现静态树不如动态树啊,虽然时间快点,但是空间要求的也太离谱了~

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1247

大意:让你输入几个单词,然后看看这有几个是可以有其他的任意两个单词或者一个单词两次,连接组成的,把他们输出就可以了

代码

View Code

#include <iostream>
#include <cstring>
#include <cstdio>
const int N=26;
const int maxn=1000000;
char s[50001][101];
using namespace std;
struct node
{
int flag;
int count;
struct node *next
;
}tree[maxn];
int t=0;
struct node *creat()
{
int i;
struct node *p;
p=&tree[t++];
p->count=1;
p->flag=0;
for(i=0;i<N;i++)
{
p->next[i]=NULL;
}
return p;
}
void insert(struct node **root,char *s)
{
int i,k;
struct node *p;
if(!(p=*root))
{
p=*root=creat();
}
i=0;
while(s[i])
{
k=s[i++]-'a';
if(p->next[k])
p->next[k]->count++;
else
p->next[k]=creat();
p=p->next[k];
}
p->flag=1;
}
int search(struct node **root,char *s)
{
int i=0,k;
struct node *p;
if(!(p=*root))
{
return 0;
}
while(s[i])
{
k=s[i++]-'a';
if(!(p->next[k]))
return 0;
p=p->next[k];
}
return p->flag;
}
int main()
{
char s1[101],s2[101],s3[101];
int l,i,j,k,c=0;
struct node *root=NULL;
while(~scanf("%s",s[c]))
{
insert(&root,s[c]);
c++;

}
for(i=0;i<c;i++)
{
memset(s1,0,sizeof(s1));
l=strlen(s[i]);
for(j=0;j<l;j++)
{
strncpy(s1,s[i],j);
if(search(&root,s1)&&search(&root,s[i]+j))
{
puts(s[i]);
break;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: