Longest Common Substring II

建立广义后缀自动机,然后在parent树上更新答案。

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
//#include
#include
#include 
#pragma GCC optimize(2)
#define up(i,a,b)  for(int i=a;i
#define dw(i,a,b)  for(int i=a;i>b;i--)
#define upd(i,a,b) for(int i=a;i<=b;i++)
#define dwd(i,a,b) for(int i=a;i>=b;i--)
//#define local
typedef long long ll;
typedef unsigned long long ull;
const double esp = 1e-6;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int inf = 1e9;
using namespace std;
ll read()
{
	char ch = getchar(); ll x = 0, f = 1;
	while (ch<'0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }
	while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
	return x * f;
}
typedef pair<int, int> pir;
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define lrt root<<1
#define rrt root<<1|1
const int N = 200010;
char s[N];
int f[N][20];
struct sam {
	int trans[N][30];
	vector<int>par;
	int len[N];
	int last, tot;
	void init(int l)
	{
		par.resize(l + 1, 0);
		upd(i, 0, l + 1)up(j, 0, 28)trans[i][j] = len[i] = 0;
		tot = 1, last = 1;
	}
	void ins(int c)
	{
		int pre = last; int now = last = ++tot;
		len[now] = len[pre] + 1;
		for (; pre && !trans[pre][c]; pre = par[pre])
			trans[pre][c] = now;
		if (!pre) {
			par[now] = 1; return;
		}
		int ano = trans[pre][c];
		if (len[ano] == len[pre] + 1) { par[now] = ano; }
		else {
			int nnow = ++tot;
			memcpy(trans[nnow], trans[ano], sizeof(trans[ano]));
			par[nnow] = par[ano];
			len[nnow] = len[pre] + 1;
			par[ano] = nnow; par[now] = nnow;
			for (; pre&&trans[pre][c] == ano; pre = par[pre])
				trans[pre][c] = nnow;
		}
	}
}S;
int main()
{
	int sz = 0;
	sz++;
	scanf("%s", s + 1);
	int len = strlen(s + 1); 
	S.init(2 * len);
	upd(i, 1, len)
		S.ins(s[i] - 'a');
	while (scanf("%s", s + 1)!=EOF)
	{
		++sz;
		len = strlen(s + 1);
		int now = 1; 
		int temp = 0;
		upd(i, 1, len)
		{
			int c = s[i] - 'a';
			if (S.trans[now][c])
				now = S.trans[now][c], temp++;
			else {
				for (; now && !S.trans[now][c]; now = S.par[now]);
				if (!now) { temp = 0; now = 1; }
				else {
					temp = S.len[now] + 1;
					now = S.trans[now][c];
				}
			}
			f[now][sz] = max(f[now][sz], temp);
		}
		dwd(i, S.tot, 1) {
			if (f[i][sz]) {
				for (int pre = S.par[i]; pre&&f[pre][sz]!=S.len[pre]; pre = S.par[pre])
				{
					f[pre][sz] = S.len[pre];
				}
			}
		}
	}
	int ans = 0;
	dwd(i, S.tot, 1)
	{
		int temp = INF;
		upd(j, 2, sz)
		{
			temp = min(temp, f[i][j]);
		}
		ans = max(ans, temp);
	}
	cout << ans << endl;
	return 0;
}

你可能感兴趣的:(广义后缀自动机)