Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

还是字典树给力!

Posted by chenxuan123456789 at 2012-07-31 18:47:29 on Problem 2503
 #include <stdio.h>
#include <malloc.h>
#include <string.h>
#define M 26
typedef struct Trie1
{
	struct Trie1 *next[M];
	char val[10];
}Trie;
Trie *root;
void init()
{
	int i;
	root=(Trie*)malloc(sizeof(Trie));
	for(i=0;i<M;i++)
	root->next[i]=NULL;
}
void bulit(Trie *T,char str1[],char str2[])
{
	int i,id,length,j;
	Trie *p,*q;
	p=root;
	length=strlen(str2);
	for(i=0;i<length;i++)
	{
		id=str2[i]-'a';
		if(p->next[id]==NULL)
		{
			q=(Trie*)malloc(sizeof(Trie));
			for(j=0;j<M;j++)
			q->next[j]=NULL;
			p->next[id]=q;
			p=q;
		}
		else
		p=p->next[id];
	}
	strcpy(p->val,str1);
}
void find(Trie *T,char str[])
{
	int i,id,length,flag=0;
	Trie *p=T;
	length=strlen(str);
	for(i=0;i<length;i++)
	{
		id=str[i]-'a';
		if(p->next[id]==NULL)
		{
			flag=1;
			printf("eh\n");
			return;
		}
		p=p->next[id];
	}
	if(!flag)
	printf("%s\n",p->val);
}
void deal(Trie *T)
{
	int i;
	if(T==NULL)
	return;
	for(i=0;i<M;i++)
	if(T->next[i]!=NULL)
	deal(T->next[i]);
	free(T);
	return;
}
int main()
{
	char a[30],b[15],c[15];
	init();
	while(gets(a)&&a[0]!='\0')
	{
		sscanf(a,"%s%s",&b,&c);
 		bulit(root,b,c);
	}
    while(gets(a)&&a[0]!='\0')
	find(root,a);
	deal(root);
     	return 1;
}



Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator