http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=33057
二维字符串匹配...大白上的题。
把匹配串的每一行当成一个串insert到AC自动机里,然后用模板串的每一行find。
如果匹配成功,那么在这个矩阵的左上角加一。
最后扫一边矩阵,如果有个地方的权值等于x,那么说明这是个匹配位置。
/* Footprints In The Blood Soaked Snow */ #include <cstdio> #include <cstring> #include <vector> #include <algorithm> using namespace std; const int maxnode = 11000, maxn = 1005, maxq = 20000; int n, m, x, y, q[maxq], cnt[maxn][maxn]; struct _acm { int son[maxnode][26], fail[maxnode], acmcnt; vector<int> val[maxnode]; void init() { memset(son, 0, sizeof(son)); acmcnt = 0; for(int i = 0; i < maxnode; i++) val[i].clear(), fail[i] = 0; } void insert(char *s, int v) { int now = 0; for(int i = 0; i < y; i++) { int &pos = son[now][s[i] - 'a']; if(!pos) pos = ++acmcnt; now = pos; } val[now].push_back(v); } void getfail() { int h = 0, t = 0; for(int i = 0; i < 26; i++) if(son[0][i]) q[t++] = son[0][i]; while(h != t) { int u = q[h++]; for(int i = 0; i < 26; i++) if(!son[u][i]) son[u][i] = son[fail[u]][i]; else fail[q[t++] = son[u][i]] = son[fail[u]][i]; } } void find(char *T, int id) { int now = 0; for(int i = 0; i < m; i++) { now = son[now][T[i] - 'a']; for(int j = 0; j < val[now].size(); j++) if(id >= val[now][j]) cnt[id - val[now][j]][i - y + 1]++; } } } acm; char str[maxn][maxn]; int main() { int T; scanf("%d", &T); while(T--) { acm.init(); memset(cnt, 0, sizeof(cnt)); scanf("%d%d", &n, &m); for(int i = 0; i < n; i++) scanf("%s", str[i]); scanf("%d%d", &x, &y); for(int i = 0; i < x; i++) { char s[maxn]; scanf("%s", s); acm.insert(s, i); } acm.getfail(); for(int i = 0; i < n; i++) acm.find(str[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; }