HDU 1686 Oulipo
- 题意:问模式串在文本串中出现过几次。
- 思路:哈希字符串匹配模板
AC CODE
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define INF 0x3f3f3f3f
#define lowbit(x) x & (-x)
#define MID (r + l) >> 1
#define lsn rt << 1
#define rsn rt << 1 | 1
#define Lson lsn, l, mid
#define Rson rsn, mid + 1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxN = 1e6 + 7;
const ull base = 233;
ull Hash[maxN], p[maxN];
void pre()
{
p[0] = 1;
for(int i = 1; i <= 1000000; i ++ )
p[i] = p[i - 1] * base;
}
ull get_hash(int l, int r, ull *g)
{
return g[r] - g[l - 1] * p[r - l + 1];
}
char tar[maxN], s[maxN];
int main()
{
pre();
int TAT; scanf("%d", &TAT);
while(TAT -- )
{
scanf("%s", tar);
ull tar_hash = 0;
int len_tar = strlen(tar);
for(int i = 1; i <= len_tar; i ++ )
tar_hash = tar_hash * base + tar[i - 1] - 'A' + 1;
scanf("%s", s);
int len = strlen(s);
Hash[0] = 0;
for(int i = 1; i <= len; i ++ )
Hash[i] = Hash[i - 1] * base + s[i - 1] - 'A' + 1;
int ans = 0;
for(int i = 1; i <= len - len_tar + 1; i ++ )
{
if(get_hash(i, i + len_tar - 1, Hash) == tar_hash)
ans ++;
}
printf("%d\n", ans);
}
return 0;
}