hdu1247(字典树)

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

题意:给你一连串的单词,输出其中可以由所给出的两个单词(可以自己和自己组成)组成的单词。

思路:建好字典树后,枚举单词的组成就好。

#include<iostream>
#include<cstring>
using namespace std;
typedef struct tree
{
	tree *next[26];
	int flag;
}tree;
tree *root=(tree *)malloc(sizeof(tree));
char s[50000][50];
void creat(char str[])
{
	int len=strlen(str);
	tree *p=root,*q;
	for(int i=0;i<len;i++)
	{
		int x=str[i]-'a';
		if(p->next[x])
		{
			p=p->next[x];
		}
		else
		{
			q=(tree *)malloc(sizeof(tree));
			q->flag=0;
			for(int j=0;j<26;j++)
				q->next[j]=NULL;
			p->next[x]=q;
			p=q;
		}
	}
	p->flag=1;

}
int find(char str[])
{
	int len=strlen(str);
	tree *p=root;
	for(int i=0;i<len;i++)
	{
		int x=str[i]-'a';
		if(p->next[x])
			p=p->next[x];
		else
			return 0;
	}
	return p->flag;
}
void del(tree *root)
{
	for(int i=0;i<26;i++)
	{
		if(root->next[i])
			del(root->next[i]);
	}
	free(root);
}
int main()
{
	for(int i=0;i<26;i++)
		root->next[i]=NULL;
	root->flag=0;
	char t[50];
	int k=0;
	while(scanf("%s",t)>0)
	{
		strcpy(s[k++],t);
		creat(t);
	}
	for(i=0;i<k;i++)
	{
		int len=strlen(s[i]);
		for(int j=1;j<len;j++)
		{
			char t1[50],t2[50];
			strcpy(t1,s[i]);
			t1[j]='\0';
			strcpy(t2,s[i]+j);
			if(find(t1)&&find(t2))
			{
				puts(s[i]);
				break;              //输出单词后就跳出循环,以免重复输出
			}
		}
	}
	del(root);
	return 0;
}

 

posted @ 2012-12-11 12:39  紫忆  阅读(867)  评论(0编辑  收藏  举报