SP1812 LCS2

  • 能匹配上子串的节点对它的所有parent都有贡献
  • 在树上转移即可
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<queue>
#define ll long long 
#define M 200010
using namespace std;

int read()
{
	int nm = 0, f = 1;
	char c = getchar();
	for(; !isdigit(c); c = getchar()) if(c == '-') f = -1;
	for(; isdigit(c); c = getchar()) nm = nm * 10 + c - '0';
	return nm * f;
}

int ch[M][26], len[M], fa[M], tim[M], a[M], cnt = 1, lst = 1, dp[M], ans[M];
char s[M];

void insert(int c)
{
	int p = ++cnt, f = lst;
	lst = p;
	len[p] = len[f] + 1;
	while(f && !ch[f][c]) ch[f][c] = p, f = fa[f];
	if(!f) fa[p] = 1;
	else
	{
		int q = ch[f][c];
		if(len[q] == len[f] + 1) fa[p] = q;
		else
		{
			int nq = ++cnt;
			fa[nq] = fa[q];
			memcpy(ch[nq], ch[q], sizeof(ch[nq]));
			len[nq] = len[f] + 1;
			fa[q] = fa[p] = nq;
			while(f && ch[f][c] == q) ch[f][c] = nq, f = fa[f];
		}
	}
}

int main()
{
	scanf("%s", s + 1);
	int l = strlen(s + 1);
	for(int i = 1; i <= l; i++) insert(s[i] - 'a');
	for(int i = 1; i <= cnt; i++) tim[len[i]]++;
	for(int i = 1; i <= cnt; i++) tim[i] += tim[i - 1];
	for(int i = 1; i <= cnt; i++) a[tim[len[i]]--] = i;
	for(int i = 1; i <= cnt; i++) ans[i] = len[i];
	while(scanf("%s", s + 1) != EOF)
	{
		memset(dp, 0, sizeof(dp));
		l = strlen(s + 1);
		int now = 1, tt = 0;
		for(int i = 1; i <= l; i++)
		{
			int c = s[i] - 'a';
			if(ch[now][c])
			{
				tt++, now = ch[now][c];
			}
			else
			{
				while(now && !ch[now][c]) now = fa[now];
				if(!now) now = 1, tt = 0;
				else tt = len[now] + 1, now = ch[now][c];
			}
			dp[now] = max(dp[now], tt);
		}
		for(int i = cnt; i >= 0; i--) dp[fa[i]] = max(dp[fa[i]], dp[i]);
		for(int i = 1; i <= cnt; i++) ans[i] = min(ans[i], dp[i]);
	}
	for(int i = 1; i <= cnt; i++) ans[i] = max(ans[i], ans[i - 1]);
	cout << ans[cnt] << "
"; 
	return 0;
}
原文地址:https://www.cnblogs.com/luoyibujue/p/10606097.html