https://www.luogu.com.cn/problem/P8306
这个数据结构的查询和插入都是O(n)的时间复杂度
代码:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<memory.h>
#include<map>
#include<vector>
#include<list>
#include<string>
#include<cmath>
#include<queue>
#include<sstream>
#include<iterator>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> Pii;
const int N = 3e6 + 5;
int tot = 0;
char s[N];
int getNum(char c)
{
if (c>='0'&&c<='9')
{
return c - '0' + 52;
}
else
{
if (c >= 'a' && c <= 'z')
{
return c - 'a';
}
else
{
return c - 'A' + 26;
}
}
}
struct Node
{
int nx[70] = {0};
int cnt=0;
}tr[N];
void insert(char target[])
{
int root = 0;
int len = strlen(target);
for (int i = 0; i < len; i++)
{
int t = getNum(target[i]);
tr[root].cnt++;
if (!tr[root].nx[t])
{
tr[root].nx[t] = ++tot;
}
root = tr[root].nx[t];
}
tr[root].cnt++;
}
int match(char target[])
{
int root = 0;
int len = strlen(target);
for (int i = 0; i < len; i++)
{
int t = getNum(target[i]);
if (!tr[root].nx[t])
{
return 0;
}
root = tr[root].nx[t];
if (i == len - 1)
{
return tr[root].cnt;
}
}
}
int main() {
//freopen("in.txt", "r", stdin);
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--)
{
int n, m;
cin >> n >> m;
for (int i = 0; i <= tot; i++)
{
tr[i].cnt = 0;
for (int j = 0; j < 70; j++)
{
tr[i].nx[j] = 0;
}
}
tot = 0;
for (int i = 1; i <= n; i++)
{
cin >> s;
insert(s);
}
for (int i = 1; i <= m; i++)
{
cin >> s;
cout << match(s)<<"\n";
}
}
return 0;
}