您的位置:首页 > 其它

poj1204 Word Puzzles

2017-01-31 14:38 387 查看
Word Puzzles

题目背景:

poj1204

分析:AC自动机的题,先将所有的匹配串建成AC自动机,然后八个方向用地图来跑即可。详细见代码。

Source:

#include
#include
#include
#include
#include
#include

using namespace std;

const int dx[9]= {0, -1, -1, 0, 1, 1, 1, 0, -1};
const int dy[9]= {0, 0, 1, 1, 1, 0, -1, -1, -1};
char ss[10000], s[1010][1010];
int f[1100000][27], first[1100000], next[1100000];
int fail[1100000], lent[1100000], queue[1100000];
int tot, cnt, head, tail, n, len, m, q;

struct data {
int x;
int y;
char dir;
} out[1010];

void build(int v, int x) {
if (x == len) {
tot++;
first[v] = tot;
lent[v] = len;
return ;
}
if (!f[v][ss[x] - 'A']) {
cnt++;
f[v][ss[x] - 'A'] = cnt;
}
build(f[v][ss[x] - 'A'], x + 1);
}

void pre_AC(void) {
head = 0, tail = 1, queue[tail] = 0;
while (head < tail) {
head++;
for (int i = 0; i < 26; ++i) {
if (f[queue[head]][i]) {
if(queue[head])
fail[f[queue[head]][i]] = f[fail[queue[head]]][i];
tail++;
queue[tail] = f[queue[head]][i];
} else f[queue[head]][i] = f[fail[queue[head]]][i];
}
}
}

void read(void) {
cin >> n, cin >> m, cin >> q;
for (int i = 0; i < n; ++i) cin >> s[i];
for (int i = 1; i <= q; ++i) {
cin >> ss;
len = strlen(ss), build(0, 0);
}
}

void find(int l, int r, int head, int type) {
if (first[head] && out[first[head]].x < 0) {
int v = first[head];
out[v].x = l - lent[head] * dx[type];
out[v].y = r - lent[head] * dy[type];
out[v].dir = type + 'A' - 1;
}
if (!(l >= 0 && l < n && r >= 0 && r < m)) return ;
while (!f[head][s[l][r] - 'A'] && head) head = fail[head];
find(l + dx[type], r + dy[type], f[head][s[l][r] - 'A'], type);
}

void get(void) {
for (int k = 1; k <= 8; ++k) {
for(int i = 0; i < n; ++i) find(i, 0, 0, k), find(i, m - 1, 0, k);
for(int i = 0; i < m; ++i) find(0, i, 0, k), find(n - 1, i, 0, k);
}
for (int i = 1; i <= q; ++i)
cout << out[i].x << " " << out[i].y << " " << out[i].dir << '\n';
}

int main(void) {
ios::sync_with_stdio(false);
cin.tie(NULL), cout.tie(NULL);
memset(out, -1, sizeof(out));
read();
pre_AC();
get();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: