题意:找在矩阵T中P矩阵出现的次数
做法:AC 自动机,或者hash。
hash版:http://blog.csdn.net/moon_no2015/article/details/47760299
AC自动机版:
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<string>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
#define ll long long
#define nn 100100
int sz;
int ch[nn][26];//建树
int val[nn];//记录尾节点
int f[nn];//表示i失配时转移到的新状态
int last[nn];//表示节点i沿着失配指针往回走时,遇到的下个单词节点编号
int pos[160];//与第i行相同的行
int cnt[1010][1010];
struct Aho
{
void init()
{
sz = 1;
memset(ch[0], 0, sizeof(ch[0]));
memset(cnt, 0, sizeof(cnt));
memset(pos, 0, sizeof(pos));
val[0] = 0;
}
int idx(char c)
{
/*
if (c >= '0' && c <= '9') return c - '0';
else if (c >= 'a'&& c <= 'z') return c - 'a' + 10;
else return c - 'A' + 36;*/
return c - 'a';
}
void insert(char* s,int v)
{
int u = 0, len = strlen(s);
for (int i = 0; i < len; i++)
{
int c = idx(s[i]);
if (!ch[u][c])
{
memset(ch[sz], 0, sizeof(ch[sz]));
val[sz] = 0;
ch[u][c] = sz++;
}
u = ch[u][c];
}
if (val[u]) pos[v] = val[u];
val[u] = v;
}
void get_f()
{
queue<int>q;
f[0] = 0;
for (int c = 0; c < 26; c++)
{
int u = ch[0][c];
if (u)
{
f[u] = 0;
q.push(u);
last[u] = 0;
}
}
while (!q.empty())
{
int r = q.front();
q.pop();
for (int c = 0; c < 26; c++)
{
int u = ch[r][c];
if (!u)
{
ch[r][c] = ch[f[r]][c];
continue;
}
q.push(u);
int v = f[r];
while (v && !ch[v][c]) v = f[v];
f[u] = ch[v][c];
last[u] = val[f[u]] ? f[u] : last[f[u]];
}
}
}
void print(int i, int j, int x)
{
if (j)
{
if (x - val[j] + 1 > 0)
cnt[x - val[j] + 1][i] ++;
int t = val[j];
while (pos[t])
{
t=pos[t];
if (x - t + 1 > 0) cnt[x - t + 1][i]++;
}
print(i, last[j], x);
}
}
void find(char* s,int x)
{
int n = strlen(s);
int j = 0;
for (int i = 0; i < n; i++)
{
int c = idx(s[i]);
j = ch[j][c];
if (val[j]) print(i, j, x);
else if (last[j]) print(i, last[j], x);
}
}
};
char t[1010][1010],p[110][110];
int main()
{
Aho ac;
int tt, n, m, x, y;
scanf("%d", &tt);
while (tt--)
{
ac.init();
scanf("%d%d", &n,&m);
for (int i = 1; i <= n; i++)
scanf("%s", t[i]);
scanf("%d%d", &x,&y);
for (int i = 1; i <= x; i++)
{
scanf("%s", p[i]);
ac.insert(p[i], i);
}
ac.get_f();
for (int i = 1; i <= n; i++)
ac.find(t[i],i);
int ans = 0;
for (int i = 1; i <= n; i++)
for (int j = 0; j < m; j++)
if (cnt[i][j] == x)
ans++;
printf("%d\n", ans);
}
return 0;
}