题意 :
- 给一长度 < 1e5 的字符串s,q < 1e5次询问,每次问一个长 < 30 的串 t 在s中出现的次数,且t不可重叠。
- 例 : “abababa“中“aba“不相交的出现的次数为2。
思路 :
- 字符串题,对母串中所有长度小于等于30的串做字符串哈希,对相同哈希值的串暴力统计答案,每个询问直接查询对应哈希值的答案。
- 也可以使用Trie/AC自动机来通过本题。
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <map>
#define endl '\n'
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
using namespace std;
const double pi = acos(-1);
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e5 + 10, P = 131;
ull h[N], p[N];
ull a[N]; // 记录每个询问串的哈希值
char str[N];
ull get(int l, int r)
{
return h[r] - h[l - 1] * p[r - l + 1];
}
int main()
{
int T;
scanf("%d", &T);
while (T -- )
{
scanf("%s", str + 1);
int len = strlen(str + 1);
p[0] = 1;
for (int i = 1; i <= len; i ++ )
{
p[i] = p[i - 1] * P;
h[i] = h[i - 1] * P + str[i];
}
int n;
scanf("%d", &n);
map<ull, int> ma; // 询问串哈希值在母串中出现的不相交的次数
map<ull, int> last; // 询问串哈希值在母串中上次出现的位置的末端
for (int i = 1; i <= n; i ++ )
{
char buf[35];
scanf("%s", buf + 1);
int size = strlen(buf + 1);
// 处理询问串哈希值
ull x = 0;
for (int j = 1; j <= size; j ++ )
x = x * P + buf[j];
a[i] = x;
ma[a[i]] = 0;
last[a[i]] = 0;
}
// 暴力枚举母串中长度小于等于30的串的哈希值
for (int i = 1; i <= len; i ++ )
{
for (int j = 0; j < 30 && i + j <= len; j ++ )
{
ull x = get(i, i + j);
// []包含了插入,count不插入,count查询是logn
if (ma.count(x) && last[x] < i)
{
ma[x] ++ ;
last[x] = i + j;
}
}
}
for (int i = 1; i <= n; i ++ )
printf("%d\n", ma[a[i]]);
}
return 0;
}