字典树~ 一种很好的母串有木有含某子串的数据结构~这是一道模板题!当然入手要先做模板题啦~
很好理解的一种树~
#include <iostream>
#include <stdio.h>
using namespace std;
struct Trienode
{
int cnt;
Trienode* next[26];
};
void insert(Trienode *root,char *s)
{
Trienode *p = root;
int i = 0;
while(s[i]!='\0')
{
//cout<<i<<endl;
int k = s[i]-'a';
if(p->next[k])
{
p->next[k]->cnt ++;
}
else
{
Trienode *tmp = new Trienode;
for(int j = 0;j < 26;j ++)
tmp->next[j] = NULL;tmp->cnt = 1;
p->next[k] = tmp;
}
p = p -> next[k];
i ++;
}
}
int search(Trienode *root,char *s)
{
int i,k;
Trienode *p = root;
i = 0;
while(s[i]!='\0')
{
k = s[i] - 'a';
if(p->next[k] == NULL) return 0;
else p = p -> next[k];
i ++;
}
return p->cnt;
}
int main()
{
char s[20];
Trienode *root = new Trienode;
root ->cnt = 0;
for(int j = 0;j < 26;j ++)
root->next[j] = NULL;
//cout<<"Das"<<endl;
while(gets(s) && s[0])
{
insert(root , s);
}
while(gets(s))
{
printf("%d\n", search(root , s));
}
return 0;
}