【Luogu P3649】[APIO2014]回文串

链接:

洛谷

题目大意:

给你一个由小写拉丁字母组成的字符串 \(s\)。我们定义 \(s\) 的一个子串的存在值为这个子串在 \(s\) 中出现的次数乘以这个子串的长度。

对于给你的这个字符串 \(s\),求所有回文子串中的最大存在值。

正文:

建一棵回文树,每一次插入字符,将当前最长回文后缀加一,统计答案时,从后往前枚举,给失配指针的节点加上本节点的值即可。

代码:

const int N = 3e5 + 10;

inline ll Read() {
	ll x = 0, f = 1;
	char c = getchar();
	while (c != '-' && (c < '0' || c > '9')) c = getchar();
	if (c == '-') f = -f, c = getchar();
	while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0', c = getchar();
	return x * f;
}

char s[N];

namespace PAM {
	int len[N], fail[N], t[N][27], s[N], cnt[N];
	int tot = -1, lst, n = 0;
	
	int New (int x) {
		len[++tot] = x;
		return tot;
	}
	
	void Build () {
		fail[New(0)] = New(-1);
		s[0] = -1;
	}
	
	int Find (int x) {
		for (; s[n - 1 - len[x]] != s[n]; x = fail[x]);
		return x;
	}
	
	void Insert (int x) {
		s[++n] = x;
		int cur = Find(lst);
		if (!t[cur][x]) {
			int now = New(len[cur] + 2);
			int tmp = Find(fail[cur]);
			fail[now] = t[tmp][x];
			t[cur][x] = now;
		}
		lst = t[cur][x];
		cnt[lst]++;
	}
	
	ll Solve() {
		ll ans = 0;
		for (int i = tot; i; i--) 
			cnt[fail[i]] += cnt[i];
		for(int i = 1; i <= tot; i++)
			ans = max(ans, 1ll * len[i] * cnt[i]);
		return ans;
	}
}

int main() {
//	freopen(".in", "r", stdin);
//	freopen(".out", "w", stdout);
	scanf ("%s", s + 1);
	int n = strlen (s + 1);
	PAM::Build();
	for (int i = 1; i <= n; i++)
		PAM::Insert(s[i] - 'a');
	printf ("%lld\n", PAM::Solve());
	return 0;
}
posted @ 2021-12-08 13:11  Jayun  阅读(14)  评论(0编辑  收藏  举报