AcWing 1283. 玄武密码
原题链接
中等
作者:
皓首不倦
,
2021-05-14 04:20:56
,
所有人可见
,
阅读 454
#include <stdio.h>
#include <string.h>
using namespace std;
int char2idx(char ch) {
if (ch == 'E') {
return 0;
} else if (ch == 'S') {
return 1;
} else if (ch == 'W') {
return 2;
} else {
return 3;
}
}
const int MAX_NODE_NUM = 20000007;
int tot = 1;
int last = 1;
struct SamNode {
int len;
int fa;
int ch[4];
} __node_pool[MAX_NODE_NUM];
char s[10000007];
char seg[105];
class SAM {
public:
void extend(int c) {
int p = last;
int np = last = ++tot;
__node_pool[np].len = __node_pool[p].len + 1;
for (; p && !__node_pool[p].ch[c]; p = __node_pool[p].fa) {
__node_pool[p].ch[c] = np;
}
if (!p) {
__node_pool[np].fa = 1;
} else {
int q = __node_pool[p].ch[c];
if (__node_pool[q].len == __node_pool[p].len + 1) {
__node_pool[np].fa = q;
} else {
int nq = ++tot;
__node_pool[nq] = __node_pool[q];
__node_pool[nq].len = __node_pool[p].len + 1;
__node_pool[q].fa = __node_pool[np].fa = nq;
for (; p && __node_pool[p].ch[c] == q; p = __node_pool[p].fa) {
__node_pool[p].ch[c] = nq;
}
}
}
}
};
void dfs(int str_pos, int max_pos, int sam_node, int& dep) {
if (str_pos+1 == max_pos) {
return;
}
char c = seg[str_pos+1];
if (__node_pool[sam_node].ch[char2idx(c)]) {
dep++;
dfs(str_pos+1, max_pos, __node_pool[sam_node].ch[char2idx(c)], dep);
}
}
int main(void) {
int n, m;
scanf("%d %d", &n, &m);
scanf("%s", s);
int str_len = strlen(s);
SAM algo;
for (int i = 0; i < str_len; i++) {
algo.extend(char2idx(s[i]));
}
int ans;
for (int i = 0; i < m; i++) {
ans = 0;
scanf("%s", seg);
dfs(-1, strlen(seg), 1, ans);
printf("%d\n", ans);
}
return 0;
}