洛谷P5496 【模板】回文自动机(PAM)

题目链接:https://www.luogu.org/problem/P5496


题意:给定字符串,求每个位置为结尾的回文串个数

思路:裸题,不过注意,是last指针在fail树上跳,并不是直接输出num数组


#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
typedef long long ll;
typedef long double ld;
const int maxn = 5e5 + 100;
const int mod = 1e9 + 7;
const int inf = 1e9;

char str[maxn];
ll fail[maxn],len[maxn],last,ch[maxn][26],n,num[maxn],cnt[maxn],tot,pos[maxn];
//len[i], 以i结尾的最长回文子串的长度 
//cnt[i]:以i结尾的最长回文子串相同的子串的个数 在count后得到全部 
//num[i] 表示以i结尾的回文串的种类数 
//str[] 存放添加的字符
//fail[] 失配后跳转到的不等于自身的最长后缀回文子串。
//pos[] 表示当前最长回文子串的结束位置 
//ch[][] 类似于字典树,指向当前字符串在两端同时加上一个字符
//last 最新添加的回文节点
// tot 总的节点个数 
// n表示添加的字符个数 
ll newnode(ll x)
{
	for(ll i = 0; i < 26; i++) //for 非多次调用回文树可省略  
		ch[tot][i] = 0;   
	cnt[tot] = 0;
	num[tot] = 0;  
	len[tot] = x;
	return tot++;
}

void init()
{
		tot = 0;
		last = 0;
		newnode(0); //偶串根节点 
		newnode(-1); //奇串根节点 
		str[0] = '#'; //0号位置设置成一个不会出现的字符 
		fail[0] = 1;  //两个根节点互指 
		fail[1] = 0;
		return ;
}

ll get_fail(ll p,ll x) 
{
	while(str[ x-len[p]-1 ] != str[x] )
		p = fail[p];
	return p;
}

void count()
{
	for(ll i = tot-1; i >= 0; i--)
		cnt[ fail[i] ] += cnt[i];
	 //父亲累加儿子的cnt,因为如果fail[v]=u,则u一定是v的子回文串!
	return ;
}

void build()  //构建回文树 
{
	ll k = 0;
	for(ll i = 1; i <= n; i++)  
	{
		if(i >= 2)
			str[i] = (str[i]-97+k)%26+97;
		
		ll tmp = get_fail(last,i);
		ll s = str[i]-'a';
		
		if(!ch[tmp][s])
		{
			ll now = newnode(len[tmp]+2);
			
			fail[now] = ch[ get_fail( fail[tmp],i )  ][ s ];
			
			ch[tmp][s] = now;
			
			num[now] = num[fail[now]]+1;
		}
		
		last = ch[tmp][s];
		pos[last] = i;
		cnt[last]++;
		k = num[last];
		cout << k << " ";
	}
	return ;
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	
	cin >> str+1;
	n = strlen(str+1);
		
	init();
	
	build();
	
	//count();
		
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值