题目连接:点击打开链接
解题思路:
字典树模板题。论一套靠谱模板的重要性!!!
完整代码:
#include <algorithm>
#include <iostream>
#include <cstring>
#include <complex>
#include <cstdio>
#include <string>
#include <cmath>
#include <queue>
using namespace std;
typedef unsigned long long LL;
const int MOD = int(1e9)+7;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-9;
const double PI = acos(-1.0); //M_PI;
const int maxn = 2000001;
int n , m;
char ss[maxn];
#define MAX 26
typedef struct node
{
int cnt; // 该节点前缀 出现的次数
struct node *next[MAX]; //该节点的后续节点
} trie;
trie mem[maxn]; //先分配好内存。 malloc 较为费时
int allocp = 0;
//初始化一个节点。nCount计数为1, next都为null
trie *creat()
{
trie * p = &mem[allocp++];
p->cnt = 1;
for(int i = 0 ; i < MAX ; i ++)
p->next[i] = NULL;
return p;
}
void insert(trie **pRoot, char *str)
{
trie *p = *pRoot;
int i = 0, k;
//一个一个的插入字符
while (str[i])
{
k = str[i] - 'a'; //当前字符 应该插入的位置
if (p->next[k])
p->next[k]->cnt++;
else
p->next[k] = creat();
p = p->next[k];
i++; //移到下一个字符
}
}
int find(trie *root, char *str)
{
if (root == NULL)
return 0;
trie *p = root;
int i = 0, k;
while (str[i])
{
k = str[i] - 'a';
if (p->next[k])
p = p->next[k];
else
return 0;
i++;
}
return p->cnt; //返回最后的那个字符 所在节点的 nCount
}
int main()
{
#ifdef DoubleQ
freopen("in.txt","r",stdin);
#endif
while(cin >> n)
{
trie *Root = creat();
for(int i = 0 ; i < n ; i ++)
{
cin >> ss;
insert(&Root , ss);
}
cin >> m;
for(int i = 0 ; i < m ; i ++)
{
cin >> ss;
cout << find(Root , ss) << endl;
}
}
return 0;
}
原文:http://blog.csdn.net/u013447865/article/details/44785385