字典树的一点小变化,多加了一个字符串进树。。
#include"stdio.h"
#include"string.h"
#include"stdlib.h"
struct tree
{
struct tree *child[26];
int n;
char str[20];
};
struct tree *root;
void insert(char s[],char *p)
{
int i,j;
int len;
struct tree *cur,*nee;
cur=root;
len=strlen(p);
for(i=0;i<len;i++)
{
if(cur->child[p[i]-'a']!=0)
{
cur=cur->child[p[i]-'a'];
cur->n++;
}
else
{
nee=(struct tree*)malloc(sizeof(struct tree));
for(j=0;j<26;j++)
nee->child[j]=0;
nee->n=1;
cur->child[p[i]-'a']=nee;
cur=nee;
cur->n=1;
}
}
strcpy(cur->str,s);
}
int find(char *p)
{
int i;
int len;
struct tree *cur;
cur=root;
len=strlen(p);
if(len==0)return 0;
for(i=0;i<len;i++)
{
if(cur->child[p[i]-'a']!=0)
cur=cur->child[p[i]-'a'];
else return 0;
}
if(i==len)
{
printf("%s\n",cur->str);
return cur->n;
}
}
int main()
{
int i,f,j;
char ss[22],s1[20],s2[20];
root=(struct tree*)malloc(sizeof(struct tree));
for(i=0;i<26;i++)
root->child[i]=0;
root->n=0;
while(gets(ss),strcmp(ss,"")!=0)
{
j=f=0;
for(i=0;ss[i]!=' ';i++)
{
s1[f++]=ss[i];
}
s1[f]='\0';
for(i=i+1;ss[i];i++)
{
s2[j++]=ss[i];
}
s2[j]=0;
insert(s1,s2);
}
while(gets(ss)!=0)
{
int ans;
ans=find(ss);
if(ans==0)
printf("eh\n");
}
return 0;
}