思路:把后面的字符串转换为数字加入到字典树中,然后再重新检索一下原来的数字的个数
注意:由于有多个实例,所以每个实例结束后必须清空一下字典树
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
#define NSIZ 5010
#define WS 100
#define N 8
char words[NSIZ][N];
typedef struct Node_
{
struct Node_ * next[10];
int isWord;
int id;
Node_()
{
for (int i = 0;i < 10; i++)
{
next[i] = 0;
}
isWord = 0;
id = -1;
}
}Node;
Node * root = 0;
int m_hash[256];
bool InsertTree(char * word)
{
if (!word || word[0] == 0)
{
return 0;
}
if (!root)
{
root = new Node();
}
int i = 0, locate = 0, n = strlen(word);
Node * tmp = root;
for (i = 0;i < n; ++i)
{
locate = word[i] - '0';
if (tmp->next[locate] == 0)
{
tmp->next[locate] = new Node();
}
tmp = tmp->next[locate];
}
tmp->isWord++;
return 0;
}
int SearchTree(char * word)
{
if (!word || word[0] == 0 || !root)
{
return 0;
}
int i = 0, locate = 0, n = strlen(word);
Node * tmp = root;
for (i = 0;i < n; ++i)
{
locate = word[i] - '0';
if (tmp->next[locate] == 0)
{
printf("0\n");
return 0;
}
tmp = tmp->next[locate];
}
printf("%d\n", tmp->isWord);
return 1;
}
bool DeleteTree(Node * root)
{
if (!root)
{
return 0;
}
int i = 0;
for (i = 0;i < 26; ++i)
{
if (root->next[i] == 0)
{
Node * tmp = root->next[i];
DeleteTree(tmp);
}
}
if (root)
{
delete root;
root = 0;
}
return 1;
}
void Init()
{
m_hash['a'] = 2;
m_hash['b'] = 2;
m_hash['c'] = 2;
m_hash['d'] = 3;
m_hash['e'] = 3;
m_hash['f'] = 3;
m_hash['g'] = 4;
m_hash['h'] = 4;
m_hash['i'] = 4;
m_hash['j'] = 5;
m_hash['k'] = 5;
m_hash['l'] = 5;
m_hash['m'] = 6;
m_hash['n'] = 6;
m_hash['o'] = 6;
m_hash['p'] = 7;
m_hash['q'] = 7;
m_hash['r'] = 7;
m_hash['s'] = 7;
m_hash['t'] = 8;
m_hash['u'] = 8;
m_hash['v'] = 8;
m_hash['w'] = 9;
m_hash['x'] = 9;
m_hash['y'] = 9;
m_hash['z'] = 9;
}
int main()
{
int i = 0, n = 0,t, n1, j, m, k;
char word1[N];
char word2[N];
Init();
while (scanf("%d", &t) != EOF )
{
while(t--)
{
scanf("%d %d", &n, &m);
for (i = 0;i < n; ++i)
{
scanf("%s", words[i]);
}
root = 0;
for (i = 0;i < m;++i)
{
scanf("%s", word1);
n1 = strlen(word1);
for (j = 0; j < n1; ++j)
{
word2[j] = m_hash[word1[j]] + '0';
}
word2[j] = 0;
InsertTree(word2);
}
for (i = 0;i < n; ++i)
{
SearchTree(words[i]);
}
DeleteTree(root);
}
}
return 0;
}