题目大意:给定一个n*m的矩阵t,在给定一个x*y的字符矩阵P,现在问在t中能够找到多少个这样的矩阵使得和P相同。
此题解法比较易懂。设cnt[r][j]表示以(r,i)为矩阵的左上角的矩阵与P对应相同的行数有多少个,这样cnt==x的就是满足题意个一个矩阵。
所以就可以利用ac自动机来做了。以p的每一行来建立自动机。
注意此题的一个陷阱:就是p的一些行可能是一样的,这样话在ac自动机里就得记录单词节点表示的是哪些行,不是某一个行。
//
// main.cpp
// uva 11019 - Matrix Matcher
//
// Created by XD on 15/8/31.
// Copyright (c) 2015年 XD. All rights reserved.
//
//此题足见算法之巧妙
#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include<vector>
#include <string.h>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <cstdio>
using namespace std ;
const int maxn = 10000 + 10 ;
const int sigma_size = 100 ;
int cnt[1001][1001] ;
int n ,m , x , y ;
char mat[1010][1010] ;
struct Ahocrosickautomata{
vector<int> row[maxn] ;
int val[maxn] ,ch[maxn][sigma_size] , f[maxn] , sz ,last[maxn];
void init()
{
sz = 1 ; memset(ch[0], 0, sizeof(ch[0])) ;
last[0] = 0 ;
for(int i = 0 ; i < maxn; i++)
{
row[i].clear() ;
}
}
int idx(char ch)
{
return ch -'a' ;
}
void insert(char *s , int v)
{
int u = 0 ;
int len = y ;
for(int i = 0 ; i <len ; i++ )
{
int j = idx(s[i]) ;
if(!ch[u][j])
{
memset(ch[sz], 0, sizeof(ch[sz])) ;
val[sz] = 0 ;
ch[u][j] = sz++ ;
}
u = ch[u][j] ;
}
val[u] = v ;
row[u].push_back(v) ;
}
void getFail()
{
queue<int > q ;
int u = 0 ;last[0] = 0 ;
for(int i = 0 ; i < sigma_size ;i++)
{
u =ch[0][i] ;
if(u) {f[u] = 0 ; q.push(u) ; last[u] = 0 ; }
}
while(!q.empty())
{
int r = q.front() ; q.pop() ;
for(int i = 0 ; i < sigma_size ;i++)
{
int u = ch[r][i] ;
if(!u) continue ;
q.push(u) ;
int v = f[r] ;
while(v && !ch[v][i]) v =f[v] ;
f[u] =ch[v][i] ;
last[u] =val[f[u]] ? f[u]:last[f[u]] ;
}
}
}
void count(int u,int r ,int c)
{
if(u)
{
int len =(int ) row[u].size() ;
for(int i = 0 ; i < len ;i++)
{
int v = row[u][i] ;
if(r+1>=v)
{
cnt[r-v+1][c - y + 1] += 1 ;
}
}
count(last[u], r, c) ;
}
}
void find(char *s,int r )
{
int u = 0 ;
for(int i = 0 ; i < m ; i++)
{
int j = idx(s[i]) ;
while(u && !ch[u][j]) u = f[u] ;
u = ch[u][j] ;
if(val[u])
{
count(u, r, i) ;
}
else if (last[u])
{
count(last[u], r, i) ;
}
}
}
};
Ahocrosickautomata ac;
int main() {
char s[110] ;
int T ; scanf("%d" ,&T) ;
while (T--) {
ac.init() ;
scanf("%d%d" ,&n,&m) ;
for (int i = 0 ; i < n; i++) {
scanf("%s",mat[i]) ;
}
scanf("%d%d" ,&x,&y) ;
for (int i = 0 ; i < x; i++) {
scanf("%s" ,s) ;
ac.insert(s, i+1) ;
}
ac.getFail() ;
memset(cnt, 0, sizeof(cnt)) ;
for (int i = 0 ; i < n; i++) {
ac.find(mat[i], i) ;
}
int ans = 0 ;
for (int i = 0; i < n ; i++) {
for (int j = 0 ; j < m;j++ ) {
if(cnt[i][j] == x )
{
ans++;
}
}
}
printf("%d\n", ans) ;
}
return 0;
}