对输入的单词建树要比先对文本建树快很多
前者是O(n*n*8),后者是(n*n*n*8),由于数据范围很大,单独对文本建树是过不了的,之前还想过建立八个方向的字典树,但是还是差不多的结果,所以对单词建树比较好
简单题,就不加注释了
#include <iostream>
using namespace std;
const int size = 1100;
const int Go[8][2] = {{-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}};
struct Trie
{
int end;
int num;
Trie *son[26];
Trie(){
end = 0;
num = -1;
for (int i = 0; i < 26; i ++){
son[i] = NULL;
}
}
};
int n, m, l;
char mapp[1100][1100];
void insert(char *x, Trie *root, int num)
{
Trie *temp;
temp = root;
int len = strlen(x);
for (int i = 0; i < len; i ++){
int k = x[i] -'A';
if (temp -> son[k] == NULL){
temp -> son[k] = new Trie;
}
temp = temp -> son[k];
}
temp -> num = num;
temp -> end ++;
}
bool check(int x, int y)
{
return (x >=0 && x < n && y >= 0 && y < m);
}
int main()
{
while (scanf("%d%d%d", &n, &m, &l) != EOF){
for (int i = 0; i < n; i ++){
scanf("%s", mapp[i]);
}
char a[1100];
Trie *root;
root = new Trie;
for (int i = 0; i < l; i ++){
scanf("%s", a);
insert(a, root, i+1);
}
int ans[1100][3]={0};
for (int i = 0; i < n; i ++){
for (int j = 0; j < n; j ++){
int kk = mapp[i][j]-'A';
if (root -> son[kk] != NULL){
for (int k = 0; k < 8; k ++){
Trie *temp2;
kk = mapp[i][j]-'A';
temp2 = root;
int xx = i+Go[k][0], yy = j+Go[k][1];
while (temp2 -> son[kk] != NULL){
if (temp2 -> end){
ans[temp2 -> num][0] = i, ans[temp2 -> num][1] = j, ans[temp2 -> num][2] = k;
}
temp2 = temp2 -> son[kk];
kk = mapp[xx][yy]-'A';
if (!check(xx, yy))break;
xx += Go[k][0], yy += Go[k][1];
}
if (temp2 -> end){
ans[temp2 -> num][0] = i, ans[temp2 -> num][1] = j, ans[temp2 -> num][2] = k;
}
}
}
}
}
for (int i = 1; i <= l; i ++){
printf("%d %d %c\n", ans[i][0], ans[i][1], char('A'+ans[i][2]));
}
}
return 0;
}