Problem Description
Input
注意:本題只有一組測試數據,處理到文件結束.
Output
Sample Input
banana band bee absolute acm ba b band abc
Sample Output
2 3 1
0
這個題是一道字典樹的題目, 算是入門練手的把 ,下面將用兩種方法來寫
一個是指針建樹 的寫法,,另一個是用數組來模擬
法一:
用字典樹模版
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
const int kind=26;
struct node
{
int count;
node *zhi[kind];
node ()
{
count=0;
for(int i=0;i<kind;i++)
{
zhi[i]=NULL;
}
}
};
node *p,*root=new node();
void createtree(char *s)
{
int i,k;
for(i=0,p=root;s[i];i++)
{
k=s[i]-'a';
if(p->zhi[k]==NULL)
{
p->zhi[k]=new node();
}
p=p->zhi[k];
p->count++;
}
}
/*void clear(node *p)
{
if(p==NULL) return;
for(int i=0;i<26;i++)
if(p->zhi[i]!=NULL)
{
clear(p->zhi[i]);
}
delete p;
root=NULL;
return ;
}*/
int find(char *s)
{
int i,k;
for(p=root,i=0;s[i];i++)
{
k=s[i]-'a';
if(p->zhi[k]==NULL)
break;
p=p->zhi[k];
}
if(s[i]) return 0;
return p->count;
}
int main()
{
char s[11];
while(gets(s)&&s[0]!='\0')
{
createtree(s);
}
while(gets(s))
{
printf("%d\n",find(s));
}
//clear(root);
return 0;
}
法二: 數組模擬
#include<stdio.h>
#include<string.h>
#define maxn 400000
int shu[maxn][26];
int pass[maxn];
int main()
{
int i;
char s[20];
int q=1,cur;
memset(shu,-1,sizeof(shu));
while(gets(s),strlen(s)>0)
{
int l=strlen(s);
cur=0;
for(i=0;i<l;i++)
{
if(shu[cur][s[i]-'a']==-1)
{
shu[cur][s[i]-'a']=q;
pass[q]=0;
q++;
}
cur=shu[cur][s[i]-'a'];
pass[cur]++;
}
}
while(gets(s))
{
int num=0,cur=0;
int l=strlen(s);
for(i=0;i<l;i++)
{
if(shu[cur][s[i]-'a']==-1)
break;
cur=shu[cur][s[i]-'a'];
if(i==l-1) num=pass[cur];
}
printf("%d\n",num);
}
return 0;
}