这题需要学习一个新算法叫 “ac自动机“
百度一下就行
#include<iostream>
#include<string.h>
using namespace std;
int drow[] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dcol[] = {0, 1, 1, 1, 0, -1, -1, -1};
int ansrow[1010], anscol[1010], ansd[1010];
int l, c, w;
char mp[1010][1010], key[1010];
int len[1010];
struct node {
node *fail;
node *next[26];
int id;
node () {
id = 0;
fail = NULL;
for (int i = 0; i < 26; i++) {
next[i] = NULL;
}
}
} *q[50005000];
node *root;
void insert(int id) {
node *p = root;
int k = len[id];
int sub;
for (int i = 0; i < k; i++) {
sub = key[i] - 'A';
if (p->next[sub] == NULL) {
p->next[sub] = new node();
}
p = p->next[sub];
}
p->id = id;
}
void build_ac() {
int in = 0;
int out = 0;
int i;
q[in++] = root;
while (in != out) {
node *p = q[out++];
node *temp;
for (i = 0; i < 26; i++) {
if (p->next[i] == NULL)continue;
if (p == root) {
p->next[i]->fail = root;
} else {
temp = p->fail;
while (temp != NULL) {
if (temp->next[i] != NULL) {
p->next[i]->fail = temp->next[i];
break;
}
temp = temp->fail;
}
if (temp == NULL) {
p->next[i]->fail = root;
}
}
q[in++] = p->next[i];
}
}
}
void query(int row, int col, int dir) {
int i, j, x;
node *p = root;
node *temp;
for (i = row, j = col; i >= 0 && i < l && j >= 0 && j < c; i += drow[dir], j += dcol[dir]) {
x = mp[i][j] - 'A';
if (p->next[x] == NULL) {
while (p != root && p->next[x] == NULL) {
p = p->fail;
}
if (p == root && p->next[x] == NULL)continue;
}
p = p->next[x];
temp = p;
while (temp != root && temp->id != -1) {
int id = temp->id;
temp->id = -1;
anscol[id] = j - (len[id] - 1) * dcol[dir];
ansrow[id] = i - (len[id] - 1) * drow[dir];
ansd[id] = dir;
temp = temp->fail;
}
}
}
int main() {
int i, j;
int coun = 0;
while (scanf("%d%d%d", &l, &c, &w) != EOF) {
if (coun > 0)printf("\n");
coun++;
for (i = 0; i < l; i++) {
scanf("%s", mp[i]);
}
root = new node();
for (i = 1; i <= w; i++) {
scanf("%s", key);
len[i] = strlen(key);
insert(i);
}
build_ac();
for (i = 0; i < c; i++) {
for (j = 0; j < 8; j++) {
query(0, i, j);
query(l - 1, i, j);
}
}
for (i = 0; i < l; i++) {
for (j = 0; j < 8; j++) {
query(i, 0, j);
query(i, c - 1, j);
}
}
for (int i = 1; i <= w; i++) {
printf("%d %d %c\n", ansrow[i], anscol[i], 'A' + ansd[i]);
}
}
}