【从0开始ACM】【LV2】【数据结构】【 AC自动机】

//POJ 1204 AC自动机模板题 
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <cstdio>
using namespace std;
#define LL long long
int L,C,W,root,last;
char mp[1005][1005];


struct node{
	int Next[26];
	int fail,count;
	char content;
}ac[100005];


int q[100005];
int head , tail;
void make_fail(  )
{
	int r = root ;
	ac[r].fail = 0;
	head = tail = 1;
	q[head] = r;
	while (head <= tail ){
		int u = q[head];
		int v;
		for(int i = 0; i<26; i++){
			if( ac[u].Next[i]){
				if( u == root )
				ac[ac[u].Next[i]].fail = root ;
				else {
					v = ac[u].fail;
					while ( v != 0){
						if( ac[v].Next[i] ){
							ac[ac[u].Next[i]].fail = ac[v].Next[i];
							break;
						}
						v = ac[v].fail;
					}
					if(v == 0) ac[ac[u].Next[i]].fail = root ;
				}
				q [ ++tail ] = ac[u].Next[i];
			}
		}
		head++;
	} 
}


void add( int c )
{
	char a[1005];
	scanf(" %s", a);
	int l = strlen( a );
	int r = root ;
	for(int i=l-1; i>=0 ; i--){
		int x = a[i]-'A';
		if( ac[r].Next[x] == 0){
			ac[r].Next[x] = ++last;
		}
		r = ac[r].Next[x];
		ac[r].content = a[i];
	}
	ac[r].count = c ;
}


struct node2{
	int x,y,dir;
}ans[1005];
int dir[8][2]={
{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}};
/*
	D7	E0	F1
	C6		G2
	B5	A4	H3
*/
void query(int x,int y,int pos)
{
	int di=pos+'A';
	if(pos<=3) di +=4;
	else di -=4;
	int r = root;
	while( x >=1 && x<= L && y>=1 && y<=C)
	{
		int c = mp[x][y] - 'A';
		while ( ac[r].Next[c]==0 && r!=root ) r= ac[r].fail;
		r = ac[r].Next[c];
		if (r==0) r=root;
		int t = r;
		while ( t != root){
			if(ac[t].count){
				int cc = ac[t].count ;
				if(ans[cc].dir>='A'&&ans[cc].dir<='Z'){
					if(ans[cc].x>x||ans[cc].x==x&&ans[cc].y>y){
						ans[cc].x=x;
						ans[cc].y=y;
						ans[cc].dir=di;
					}
				}
				else {
					ans[cc].x=x;
					ans[cc].y=y;
					ans[cc].dir=di;
				}
			}
			t = ac[t].fail;
		}
		x += dir[pos][0];
		y += dir[pos][1];
	}
}
void search( )
{
	for (int i =1 ;i<=L;i++){
		query(i,1,1);query(i,1,2);query(i,1,3);
		query(i,C,5);query(i,C,6);query(i,C,7);
	}
	for (int i =1; i<=C; i++){
		query(1,i,3);query(1,i,4);query(1,i,5);
		query(L,i,7);query(L,i,0);query(L,i,1);
	}
	for(int i = 1; i<=W; i++)
		printf("%d %d %c\n",ans[i].x-1,ans[i].y-1,ans[i].dir);
}


void init( )
{
	root = last = 1;
	memset(ac, 0 ,sizeof(ac));
	memset(ans, 0 ,sizeof(ans));
}


int main()
{
	scanf("%d%d%d",&L,&C,&W);
	init();
	for(int i=1; i<=L; i++)
		for(int j=1; j<=C; j++)
		scanf(" %c",&mp[i][j] );
	for(int i=1; i<=W; i++){
		add ( i );
	}
	make_fail();
	search();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值