題目連接:點擊打開鏈接
解題思路:
字典樹模板題。論一套靠譜模板的重要性!!!
完整代碼:
#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;
}