【Uva11019】Matrix Matcher【AC自动机】【二维字符串匹配】

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值