频道栏目
首页 > 资讯 > 其他 > 正文

【BZOJ4327】【JSOI2012】玄武密码 编程题

18-02-07        来源:[db:作者]  
收藏   我要投稿

【思路要点】

后缀自动机模板题。时间复杂度\(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;
}
相关TAG标签
上一篇:【BZOJ3992】序列统计(动态规划,NTT) 编程题
下一篇:Leetcode 73 Python 编程题
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站