hdu5658 CA Loves Palindromic 回文树

回文树在处理回文方面真的比manacher要好用得多。。。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#define REP(i,a,b) for(int i=a;i<=b;i++)
#define MS0(a) memset(a,0,sizeof(a))

using namespace std;

typedef long long ll;
const int maxn=1100;
const int INF=1e9+10;

int n,q;
char s[maxn];
int l,r;
ll ans[maxn][maxn];

struct PalinTree
{
    int ch[maxn][26],f[maxn];
    int n,tot,last;
    int len[maxn],cnt[maxn];
    int s[maxn];
    int newnode(int l)
    {
        MS0(ch[tot]);
        cnt[tot]=0;len[tot]=l;
        return tot++;
    }
    void init()
    {
        tot=0;
        newnode(0);
        newnode(-1);
        last=0;n=0;
        s[n]=-1;f[0]=1;
    }
    int get_fail(int x)
    {
        while(s[n-len[x]-1]!=s[n]) x=f[x];
        return x;
    }
    void add(int c)
    {
        c-='a';
        s[++n]=c;
        last=get_fail(last);
        if(!ch[last][c]){
            int cur=newnode(len[last]+2);
            f[cur]=ch[get_fail(f[last])][c];
            ch[last][c]=cur;
        }
        last=ch[last][c];
        cnt[last]++;
    }
};PalinTree pt;

void Init()
{
    int len=strlen(s+1);
    REP(l,1,len){
        pt.init();
        REP(r,l,len){
            pt.add(s[r]);
            ans[l][r]=pt.tot-2;
        }
    }
}

int main()
{
    freopen("in.txt","r",stdin);
    while(~scanf("%d",&n)){
        scanf("%s",s+1);
        Init();
        scanf("%d",&q);
        while(q--){
            scanf("%d%d",&l,&r);
            printf("%I64d\n",ans[l][r]);
        }
    }
    return 0;
}
View Code

这题用回文树做的话,又是一道水题啊水题。。。。

posted @ 2016-04-07 01:14  __560  阅读(442)  评论(0编辑  收藏  举报