poj2001(字典树)

http://acm.hust.edu.cn:8080/judge/problem/viewProblem.action?id=11157

#include<iostream>
#include<cstring>
using namespace std;
typedef struct tree 
{
	int num,flag;
	tree *next[26];
}tree;
tree *root;
char s[1005][25];
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]==NULL)
		{
			q=(tree *)malloc(sizeof(tree));
			q->flag=0;
			q->num=1;
			for(int j=0;j<26;j++)
				q->next[j]=NULL;
			p->next[x]=q;
			p=q;
		}
		else
		{
			p->next[x]->num++;
			p=p->next[x];
		//	printf("%d\t",p->num);
		}
	}
	p->flag=-1;
}
void del(tree *p)
{
	for(int i=0;i<26;i++)
	{
		if(p->next[i])
			del(p->next[i]);
	}
	free(p);
}
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])
			return i;
		else
		{
			if(p->next[x]->num==1)
				return i;
			p=p->next[x];
		}
	}
	return len;
}
int main()
{
	int i=0;
	root=(tree *)malloc(sizeof(tree));
	for(i=0;i<26;i++)
		root->next[i]=NULL;
	root->flag=0;
	root->num=0;
	i=0;
	while(gets(s[i])>0&&s[i][0]!='\0')
	{
		creat(s[i]);
		i++;
	}
	for(int j=0;j<i;j++)
	{
		int len=find(s[j]);
	//	printf("%d\n",len);
		++len;
		printf("%s ",s[j]);
		s[j][len]='\0';
		printf("%s\n",s[j]);
	}
         //del(root);
return 0; }

 

posted @ 2012-12-24 14:01  紫忆  阅读(743)  评论(0编辑  收藏  举报