注意:本题只有一组测试数据,处理到文件结束.
字典树的问题,自己改的模板,鼓励一下,以后就用这个模板了!
#include <algorithm>
#include<vector>
#include<map>
#include<set>
#include<string>
#include<iostream>
using namespace std;
#define max(x,y) ((x)>(y)?(x):(y))
const int sonnum=26,base='a';
struct Trie
{
int num;
bool leave;
Trie *child[sonnum];
};
Trie *NewTrie()
{
Trie *temp = new Trie;
temp->num = 1;
temp->leave = false;
for(int i=0;i<sonnum;i++)
temp->child[i] = NULL;
return temp;
}
// insert a new word to Trie tree
void Insert(Trie *node,char *s,int len)
{
for(int i=0;i<len;++i)
{
if(!node->child[s[i] - base])
node->child[s[i] - base] = NewTrie();
else
node->child[s[i] - base]->num++;
node = node->child[s[i] - base];
}
node->leave = true;
}
// delete the whole tree
void Delete(Trie *node)
{
if(node)
{
for(int i=0;i<sonnum;i++)
if(node->child[i])
Delete(node->child[i]);
delete node;
}
}
//trie to find the current word
Trie* Find(Trie *node,char *s,int len)
{
for(int i=0;i<len;i++)
if(node->child[s[i] - base])
node=node->child[s[i] - base];
else
return NULL;
return node;
}
int main ()
{
ifstream cin("test.txt");
char str[12];
Trie *root = new Trie();
Trie *tmp;
int i=0;
while(cin.getline(str,12) && strcmp(str,""))
{
Insert(root,str,strlen(str));
}
while(cin>>str)
{
tmp = Find(root,str,strlen(str));
if(tmp)
cout<<tmp->num<<endl;
else
cout<<0<<endl;
}
return 0 ;
}