您的位置:首页 > 其它

[UVA11019] Matrix Matcher && AC自动机

2015-01-16 12:58 302 查看
本来RK在这道题快得多的....

自动机就自动机吧

Pc[i]表示编号 Next[i]表示下一个相同行 Now在全局表示当前处理到了第几行

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<queue>
#define SF scanf
#define PF printf
#define max(a, b) ((a) < (b) ? (b) : (a))
using namespace std;
typedef long long LL;
const int MAXN = 1000;
const int MAXL = 10000;
const int SZ = 26;
char s[MAXN+10][MAXN+10], P[MAXN/10+10][MAXN/10+10];
int ans, Now;
int Pc[MAXN+10], Next[MAXN+10], Len[MAXN+10];
int cnt[MAXN+10][MAXN+10];
struct Aho_Corasick
{
	int ch[MAXL+10][SZ], Ncnt, val[MAXL+10];
	int f[MAXL+10], last[MAXL+10];
	void init() { 
		memset(ch[0], 0, sizeof(ch[0])); 
		Ncnt = 1; 
	}
	void Match(int pos, int v)
	{
		int cur = Pc[v-1];
		int c = pos - Len[cur] + 1;
		while(cur >= 0) {
			if(Now >= cur)
				cnt[Now - cur][c]++;
			cur = Next[cur];
		}
	}
	void New() {
		memset(ch[Ncnt], 0, sizeof(ch[Ncnt]));
		val[Ncnt] = 0;
	}
	inline int ID(char c) { return c - 'a'; }
	void insert(char *s, int v)
	{
		int u = 0, n = strlen(s);
		for(int i = 0; i < n; i++)
		{
			int c = ID(s[i]);
			if(!ch[u][c]) {
				New();
				ch[u][c] = Ncnt++;
			}
			u = ch[u][c];
		}
		val[u] = v;
	}
	void getFail()
	{
		queue <int> q;
		f[0] = 0;
		for(int c = 0; c < SZ; 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 < SZ; 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 add(int i, int j) {
		if(j) {
			Match(i, val[j]);
			add(i, last[j]);
		}
	}
	void solve(char *s) {
		int n = strlen(s), j = 0;
		for(int i = 0; i < n; i++)
		{
			int c = ID(s[i]);
			j = ch[j][c];
			if(val[j]) add(i, j);
			else if(last[j]) add(i, last[j]);
		}
	}
}ac;
int main()
{
	int T; SF("%d", &T); while(T--) {
		int n, m, x, y;
		SF("%d%d", &n, &m);
		for(int i = 0; i < n; i++) SF("%s", s[i]);
		SF("%d%d", &x, &y);
		ac.init();
		for(int i = 0; i < x; i++) {
			SF("%s", P[i]);
			Len[i] = strlen(P[i]);
			Pc[i] = i;
			Next[i] = -1;
			for(int j = 0; j < i; j++) if(!strcmp(P[i], P[j])) {
				Pc[i] = j;
				Next[i] = Next[j];
				Next[j] = i;
				break;
			}
			if(Pc[i] == i) ac.insert(P[i], i + 1);
		}
		ac.getFail();
		memset(cnt, 0, sizeof(cnt));
		for(Now = 0; Now < n; Now++) 
			ac.solve(s[Now]);
		ans = 0;
		for(int i = 0; i < n - x + 1; i++)
			for(int j = 0; j < m - y + 1; j++)
				if(cnt[i][j] == x) ans++;
		PF("%d\n", ans);
	}
	return 0;
}
/*
5
she
he
say
shr
her
yasherhs 
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: