【BZOJ4327】【JSOI2012】玄武密码

【题目链接】

  • 点击打开链接

【思路要点】

  • 后缀自动机模板题。
  • 时间复杂度\(O(字符串长度)\)。

【代码】

#include
using namespace std;
const int MAXN = 20000005;
const int MAXC = 4;
template  void read(T &x) {
	x = 0; int f = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
	for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
	x *= f;
}
template  void write(T x) {
	if (x < 0) x = -x, putchar('-');
	if (x > 9) write(x / 10);
	putchar(x % 10 + '0');
}
template  void writeln(T x) {
	write(x);
	puts("");
}
struct SuffixAutomaton {
	int n, root, size, last, child[MAXN][MAXC];
	int father[MAXN], depth[MAXN];
	int new_node(int dep) {
		father[size] = 0;
		depth[size] = dep;
		memset(child[size], 0, sizeof(child[size]));
		return size++;
	}
	int index(char x) {
		if (x == 'S') return 0;
		if (x == 'N') return 1;
		if (x == 'E') return 2;
		return 3;
	}
	void Extend(int ch) {
		int np = new_node(depth[last] + 1);
		int p = last;
		while (child[p][ch] == 0) {
			child[p][ch] = np;
			p = father[p];
		}
		if (child[p][ch] == np) last = np;
		else {
			int q = child[p][ch];
			if (depth[p] + 1 == depth[q]) father[np] = q;
			else {
				int nq = new_node(depth[p] + 1);
				father[nq] = father[q];
				father[np] = father[q] = nq;
				memcpy(child[nq], child[q], sizeof(child[nq]));
				while (child[p][ch] == q) {
					child[p][ch] = nq;
					p = father[p];
				}
			}
			last = np;
		}
	}
	void init(int x, char *s) {
		n = x; size = 0;
		root = last = new_node(0);
		for (int i = 1; i <= n; i++)
			Extend(index(s[i]));
	}
	void calc(char *t) {
		int len = strlen(t + 1);
		int now = root;
		for (int i = 1; i <= len; i++) {
			if (child[now][index(t[i])] == 0) {
				writeln(i - 1);
				return;
			}
			now = child[now][index(t[i])];
		}
		writeln(len);
	}
} SAM;
int n, m;
char s[MAXN], t[MAXN];
int main() {
        read(n), read(m);
        scanf("\n%s", s + 1);
        SAM.init(n, s);
        for (int i = 1; i <= m; i++) {
        	scanf("\n%s", t + 1);
        	SAM.calc(t);
        }
	return 0;
}


你可能感兴趣的:(【OJ】BZOJ,【类型】做题记录,【资料】模板题,【数据结构】后缀自动机与后缀树)