POJ2774 Long Long Message - 后缀数组

Description

求两个字符串的最长公共子串。

Solution

把两个字符串拼起来,问题就转化为了求任意两个后缀的 \(lcp\) 的最大长度。

显然这个最大长度是 \(height_i\) 的值,\(\text{SA}\) 求解即可。

需要注意的是,对于 \(height_i\) 需要判断一下 \(SA_i\)\(SA_{i-1}\) 是否在不同的串中。

Code

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

const int _ = 2e5 + 10;
int N, n, m, rnk[_], sa[_], height[_];
char s[_];

void SA() {
	static int a[_], buc[_], fir[_], sec[_], tmp[_];
	static char t[_];
	copy(s + 1, s + N + 1, t + 1);
	sort(t + 1, t + N + 1);
	char *end  = unique(t + 1, t + N + 1);
	for (int i = 1; i <= N; ++i) a[i] = lower_bound(t + 1, end, s[i]) - t;
	for (int i = 1; i <= N; ++i) ++buc[a[i]];
	for (int i = 1; i <= N; ++i) buc[i] += buc[i - 1];
	for (int i = 1; i <= N; ++i) rnk[i] = buc[a[i] - 1] + 1;
	for (int len = 1; len <= N; len <<= 1) {
		for (int i = 1; i <= N; ++i) {
			fir[i] = rnk[i];
			sec[i] = i + len > N ? 0 : rnk[i + len];
		}
		fill(buc + 1, buc + N + 1, 0);
		for (int i = 1; i <= N; ++i) ++buc[sec[i]];
		for (int i = 1; i <= N; ++i) buc[i] += buc[i - 1];
		for (int i = 1; i <= N; ++i) tmp[N - --buc[sec[i]]] = i;
		fill(buc + 1, buc + N + 1, 0);
		for (int i = 1; i <= N; ++i) ++buc[fir[i]];
		for (int i = 1; i <= N; ++i) buc[i] += buc[i - 1];
		for (int i, j = 1; j <= N; ++j) {
			i = tmp[j];
			sa[buc[fir[i]]--] = i;
		}
		bool only = true;
		for (int i, j = 1, last = 0; j <= N; ++j) {
			i = sa[j];
			if (!last) rnk[i] = 1;
			else if (fir[i] == fir[last] && sec[i] == sec[last])
				rnk[i] = rnk[last], only = false;
			else rnk[i] = rnk[last] + 1;
			last = i;
		}
		if (only) break;
	}
	for (int i = 1, k = 0; i <= N; ++i) {
		if (rnk[i] == 1) k = 0;
		else {
			if (k > 0) --k;
			int j = sa[rnk[i] - 1];
			while (i + k <= N && j + k <= N && a[i + k] == a[j + k]) ++k;
		}
		height[rnk[i]] = k;
	}
}

bool check(int i, int j) {
	return (i <= n && j > n) | (i > n && j <= n);
}

int main() {
#ifndef ONLINE_JUDGE
	freopen("message.in", "r", stdin);
	freopen("message.out", "w", stdout);
#endif
	scanf("%s", s + 1);
	n = N = strlen(s + 1);
	scanf("%s", s + N + 1);
	N = strlen(s + 1);
	m = N - n;
	SA();
	int ans = 0;
	for (int i = 2; i <= N; ++i)
		if (check(sa[i], sa[i - 1])) ans = max(ans, height[i]);
	printf("%d\n", ans);
	return 0;
}
posted @ 2020-01-06 22:07  newbielyx  阅读(131)  评论(0编辑  收藏  举报