SP1812 LCS2 - Longest Common Substring II

\(\color{#0066ff}{ 题目描述 }\)

题面描述 给定一些字符串,求出它们的最长公共子串 输入格式 输入至多\(10\) 行,每行包含不超过\(100000\) 个的小写字母,表示一个字符串 输出格式 一个数,最长公共子串的长度 若不存在最长公共子串,请输出\(0\)

\(\color{#0066ff}{输入格式}\)

几个字符串

\(\color{#0066ff}{输出格式}\)

一个整数,为 所求答案

\(\color{#0066ff}{输入样例}\)

alsdfkjfjkdsal
fdjskalajfkdsla
aaaajfaaaa

\(\color{#0066ff}{输出样例}\)

2

\(\color{#0066ff}{数据范围与提示}\)

none

\(\color{#0066ff}{ 题解 }\)

对第一个字符串建立SAM

每个点维护一个max,min ,分别代表当前字符串匹配的最大len, 全局匹配的最大len

匹配之前,鸡排搞一下,方便递推

每次匹配的时候,max清0, 匹配到哪,就用当前匹配长度len更新当前节点max

匹配完一个后,开始按顺序(已经排好了)扫每个点,更新它的父亲

他父亲的max要跟min(父亲的len, 当前的max)取max

因为叶子维护的是整个前缀,所以不会存在超出的情况,但父亲不一样,要跟自己的len取min,然后跟自己的max取max挺绕的

最后跟所有节点去max就是ans了

#include<bits/stdc++.h>
using namespace std;
#define LL long long
LL in() {
	char ch; int x = 0, f = 1;
	while(!isdigit(ch = getchar()))(ch == '-') && (f = -f);
	for(x = ch ^ 48; isdigit(ch = getchar()); x = (x << 1) + (x << 3) + (ch ^ 48));
	return x * f;
}
const int maxn = 2e5 + 5;
const int inf = 0x7f7f7f7f;
struct SAM {
protected:
	struct node {
		node *ch[26], *fa;
		int len, siz, max, min;
		node(int len = 0, int siz = 0, int max = 0, int min = inf): fa(NULL), len(len), siz(siz), max(max), min(min) {
			memset(ch, 0, sizeof ch);
		}
	};
	node *root, *tail, *lst;
	node pool[maxn], *id[maxn];
	int c[maxn];
	void extend(int c) {
		node *o = new(tail++) node(lst->len + 1, 1), *v = lst;
		for(; v && !v->ch[c]; v = v->fa) v->ch[c] = o;
		if(!v) o->fa = root;
		else if(v->len + 1 == v->ch[c]->len) o->fa = v->ch[c];
		else {
			node *n = new(tail++) node(v->len + 1), *d = v->ch[c];
			std::copy(d->ch, d->ch + 26, n->ch);
			n->fa = d->fa, d->fa = o->fa = n;
			for(; v && v->ch[c] == d; v = v->fa) v->ch[c] = n;
		}
		lst = o;
	}
	void clr() {
		tail = pool;
		root = lst = new(tail++) node();
	}
public:
	SAM() { clr(); }
	void ins(char *s) { for(char *p = s; *p; p++) extend(*p - 'a'); }
	void getid() {
		int maxlen = 0;
		for(node *o = pool; o != tail; o++) c[o->len]++, maxlen = std::max(maxlen, o->len);
		for(int i = 1; i <= maxlen; i++) c[i] += c[i - 1];
		for(node *o = pool; o != tail; o++) id[--c[o->len]] = o;
	}
	void match(char *s) {
		node *o = root;
		int len = 0;
		for(char *p = s; *p; p++) {
			int pos = *p - 'a';
			if(o->ch[pos]) o = o->ch[pos], len++;
			else {
				while(o && !o->ch[pos]) o = o->fa;
				if(!o) o = root, len = 0;
				else len = o->len + 1, o = o->ch[pos];
			}
			o->max = std::max(o->max, len);
		}
		for(int i = tail - pool - 1; i; i--) {
			node *o = id[i];
			if(o->fa) o->fa->max = std::max(o->fa->max, std::min(o->max, o->fa->len));
			o->min = std::min(o->min, o->max);
			o->max = 0;
		}
	}
	int getans() {
		int ans = 0;
		for(int i = tail - pool - 1; i; i--) ans = std::max(ans, id[i]->min);
		return ans;
	}
}sam;
char s[maxn];
int main() {
	scanf("%s", s);
	sam.ins(s);
	sam.getid();
	while(~scanf("%s", s)) sam.match(s);
	printf("%d\n", sam.getans());
	return 0;
}
posted @ 2019-01-10 20:41  olinr  阅读(191)  评论(0编辑  收藏  举报