题意:如题。
#include <iostream>
#include <string>
#include <cstring>
#include <sstream>
using namespace std;
struct Trie
{
int count;
Trie* next[26];
Trie() : count(0) { memset(next, 0, sizeof (next)); }
};
void insert(Trie* root, string& s, int len)
{
Trie* p = root;
int i;
if (p == NULL)
p = new Trie;
p->count++;
for (i = 0; i < len; ++i)
{
if (p->next[s[i] - 'a'] == NULL)
p->next[s[i] - 'a'] = new Trie;
p = p->next[s[i] - 'a'];
p->count++;
}
}
int search(Trie* root, string& s, int len)
{
Trie* p = root;
int i;
if (p == NULL)
return 0;
for (i = 0; i < len; ++i)
{
if (p->next[s[i] - 'a'] == NULL)
return 0;
p = p->next[s[i] - 'a'];
}
return p->count;
}
void freeTrie(Trie* root)
{
if (root == NULL)
return;
for (int i = 0; i < 26; ++i)
if (root->next[i] != NULL)
freeTrie(root->next[i]);
delete root;
}
int main()
{
Trie* root = new Trie;
string line;
int len;
while (getline(cin, line), (len = line.length()))
insert(root, line, len);
while (getline(cin, line))
cout << search(root, line, line.length()) << endl;
freeTrie(root);
}