以hdu1251统计难题为例
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct node
{
int n;
node *next[26];
}*trid;
struct node * tree ;
void build(char *ch)
{
int len=strlen(ch);
int i,j;
if(len==0) //插入为0...直接返回
return ;
trid current, temp; //current表示当前节点,temp表示新的被tree指向的节点
current=tree;
for(i=0;i<len;i++)
{
if(current->next[ch[i]-'a']!=0) //重要!! 判断该节点是否为空指针(则前缀没在树中)
{
current=current->next[ch[i]-'a']; //将current指向它的next,形成链表
// (如果是用tree指的话,后面将都连在tree上,形成不了链表)
current->n= current->n+1;
}
else
{
temp=(trid)malloc(sizeof(node));
for(j=0;j<26;j++) // 每次新建节点后都要预处理!!!!
temp->next[j]=0;
current->next[ch[i]-'a']=temp; //current指向temp
current=temp; //(链表构造规则:先指向,后转移)
temp->n=1;
}
}
return ;
}
int find(char *s)
{
int i;
int len=strlen(s);
if(len==0)
return 0;
trid current=tree;
for(i=0;i<len;i++)
{
if(current->next[s[i]-'a']!=0)
current=current->next[s[i]-'a'];
else
return 0;
}
return current->n; //输出前缀为s的单词长度
}
int main()
{
char ch[20],s[10];
int i;
tree=(trid)malloc(sizeof(node));
for(i=0;i<26;i++) // 对next , n 进行预处理 next表示下一位的指针,n表示出现的次数
tree->next[i]=0;
while(gets(ch),strcmp(ch,"")!=0) //遇到空一行结束字母表的输入
build(ch);
while(scanf("%s",s)!=EOF)
{
i=find(s);
printf("%d\n",i);
}
return 0;
}