【BZOJ3676】【APIO2014】回文串

本文介绍了一道关于回文树的数据结构与算法题目。通过使用C++实现了一个回文树结构,该结构能够高效地处理字符串问题,特别是涉及回文子串的问题。文章详细解释了如何构建回文树,并提供了完整的代码示例。通过递增更新每个节点的计数,最终计算出最长回文子串的长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目链接】

【思路要点】

  • 回文树模板题。
  • 时间复杂度\(O(|S|)\)。

【代码】

#include<bits/stdc++.h>
using namespace std;
#define MAXN	300005
struct Palindromic_Tree {
	int child[MAXN][26], father[MAXN];
	int depth[MAXN], cnt[MAXN];
	int size, last, len;
	char s[MAXN];
	int new_node(int length) {
		memset(child[size], 0, sizeof(child[size]));
		father[size] = 0;
		depth[size] = length;
		cnt[size] = 0;
		return size++;
	}
	void Extend(int ch, int pos) {
		int p = last;
		while (s[pos - depth[p] - 1] != s[pos])
			p = father[p];
		if (!child[p][ch]) {
			int now = new_node(depth[p] + 2), fa = father[p];
			while (s[pos - depth[fa] - 1] != s[pos])
				fa = father[fa];
			father[now] = child[fa][ch];
			if (father[now] == 0) father[now] = 1;
			child[p][ch] = now;
		}
		last = child[p][ch];
		cnt[last]++;
	}
	void init(char *x) {
		len = strlen(x + 1);
		for (int i = 1; i <= len; i++)
			s[i] = x[i];
		size = 0;
		new_node(-1);
		new_node(0);
		father[0] = father[1] = 0;
		depth[0] = -1;
		last = 1;
		for (int i = 1; i <= len; i++)
			Extend(s[i] - 'a', i);
	}
	long long getans() {
		long long ans = 0;
		for (int i = size - 1; i > 0; i--) {
			cnt[father[i]] += cnt[i];
			ans = max(ans, (long long) cnt[i] * depth[i]);
		}
		return ans;
	}
} PT;
char s[MAXN];
int main() {
	scanf("%s", s + 1);
	PT.init(s);
	printf("%lld\n", PT.getans());
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值