统计难题
Problem Description
Input
注意:本题只有一组测试数据,处理到文件结束.
Output
Sample Input
banana band bee absolute acm ba b band abc
Sample Output
2 3 1 0
解析:字典树的应用
#include"stdio.h"
#include"string.h"
#include"stdlib.h"
typedef struct dictree
{
int n; //表示字符串出现的次数
dictree *child[26]; //因为都是小写字母,所以每个节点都有26个孩子,如果有大写字母则有52个,加数字是62个
};
dictree *root; //定义树根
/*初始化树根,给树根的26个孩子赋值为空*/
void initree()
{
int i;
root=(dictree *)malloc(sizeof(dictree));
for(i=0;i<26;i++)
root->child[i]=NULL;
root->n=0;
}
void insertString(char s[])
{
int i,j,len;
len=strlen(s);
dictree *current,*newnode; //current指针指向当前节点。newnode指针指向新开辟的节点
current=root;
for(i=0;i<len;i++)
{
if(current->child[s[i]-'a']==NULL) //如果当前树中没有字符s[i],则以该节点为父节点,再产生新的节点,且n值为0,这棵子树中
{
newnode=(dictree *)malloc(sizeof(dictree));
for(j=0;j<26;j++)
newnode->child[j]=NULL;
current->child[s[i]-'a']=newnode; //产生的新节点作为当前节点的孩子
current=newnode; //current指针指向新产生的节点
current->n=1;
}
else //当前有这个节点 ,则沿着这棵子树往下搜索。
{
current=current->child[s[i]-'a'];
current->n++; //记录输入的字符串能到这个节点的个数。比如输入abcd和ab则到b这个节点的个数是2。
}
}
}
int find(char s[])
{
int i,j,k;
int len;
len=strlen(s);
if(len==0)
return 0;
dictree *current;
current=root;
for(i=0;i<len;i++) //类似于hash。到了一个节点查找下一个字母时,由于存储是用 child[s[i]-'a']存储的,所以查找也只要用child[s[i]-'a']查找。
{
if(current->child[s[i]-'a']!=0)
current=current->child[s[i]-'a'];
else
return 0;
}
return current->n;
}
int main()
{
char temp[11];
int i;
initree();
while(gets(temp),strcmp(temp,"")!=0)
insertString(temp);
while(gets(temp)!=0)
printf("%d\n",find(temp));
return 0;
}