【CodeVS 3160】最长公共子串

http://codevs.cn/problem/3160/
看了好久的后缀自动机_(:з」∠)_
对A串建立SAM,用B串去匹配A串SAM,如果在当前节点走不下去,就跳到当前节点的parent(类似AC自动机的失配指针),找到当前节点代表的状态中长度最长的后缀,并看能不能继续走下去。
如果跳到了能继续走下去的节点,就更新L为这个节点的max+1,同时在这个节点往下走一步(更新L和继续走不能颠倒,因为往下走一步之后的节点的max值并不能确定)。
照搬clj课件里的模板

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

struct State {
	State *par, *go[26];
	int val;
	State(int _val) : par(0), val(_val)
		{memset(go, 0, sizeof(go));}
} *root, *last;

void extend(int w) {
	State *p = last;
	State *np = new State(p->val + 1);
	while (p && p->go[w] == 0)
		p->go[w] = np, p = p->par;
	if (p == 0) np->par = root;
	else {
		State *q = p->go[w];
		if (p->val + 1 == q->val) np->par = q;
		else {
			State *nq = new State(p->val + 1);
			memcpy(nq->go, q->go, sizeof(q->go));
			nq->par = q->par;
			q->par = np->par = nq;
			while (p && p->go[w] == q)
				p->go[w] = nq, p = p->par;
		}
	}
	last = np;
}

int la, lb;
char A[100003], B[100003];

void work() {
	State *tmp = root;
	int ans = 0, x, L = 0;
	for(int i = 1; i <= lb; ++i) {
		x = B[i] - 'a';
		if (tmp->go[x]) {
			tmp = tmp->go[x];
			++L;
		} else {
			while (tmp && tmp->go[x] == 0)
				tmp = tmp->par;
			if (tmp == 0) tmp = root, L = 0;
			else L = tmp->val + 1, tmp = tmp->go[x];
		}
		ans = max(ans, L);
	}
	printf("%d\n", ans);
}

int main() {
	root = last = new State(0);
	scanf("%s%s", A + 1, B + 1);
	la = strlen(A + 1); lb = strlen(B + 1);
	for(int i = 1; i <= la; ++i)
		extend(A[i] - 'a');
	work();
	return 0;
}
posted @ 2016-09-27 09:23  abclzr  阅读(176)  评论(0编辑  收藏  举报