【SPOJ】NUMOFPAL

【SPOJ】NUMOFPAL - Number of Palindromes(Manacher,回文树)

题面

洛谷
求一个串中包含几个回文串

题解

Manacher傻逼题
只是用回文树写写而已。。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define ll long long
#define RG register
#define MAX 10000
inline int read()
{
    RG int x=0,t=1;RG char ch=getchar();
    while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
    if(ch=='-')t=-1,ch=getchar();
    while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();
    return x*t;
}
int n;
char s[MAX];
int size[MAX];
struct PT
{
	struct Node
	{
		int son[26];
		int ff,len;
	}t[MAX];
	int last,tot;
	void init()
	{
		t[tot=1].len=-1;
		t[0].ff=t[1].ff=1;
	}
	void extend(int c,int n,char *s)
	{
		int p=last;
		while(s[n-t[p].len-1]!=s[n])p=t[p].ff;
		if(!t[p].son[c])
		{
			int v=++tot,k=t[p].ff;
			while(s[n-t[k].len-1]!=s[n])k=t[k].ff;
			t[v].len=t[p].len+2;
			t[v].ff=t[k].son[c];
			t[p].son[c]=v;
		}
		++size[last=t[p].son[c]];
	}
	void Calc()
	{
		for(int i=tot;i;--i)size[t[i].ff]+=size[i];
	}
}PT;
int ans;
int main()
{
	PT.init();
	scanf("%s",s+1);
	n=strlen(s+1);
	for(int i=1;i<=n;++i)PT.extend(s[i]-97,i,s);
	PT.Calc();
	for(int i=2;i<=PT.tot;++i)ans+=size[i];
	printf("%d
",ans);
	return 0;
}


原文地址:https://www.cnblogs.com/cjyyb/p/8463391.html