HDU 5658 CA Loves Palindromic (回文树。)

Problem Description
CA loves strings, especially loves the palindrome strings.
One day he gets a string, he wants to know how many palindromic substrings in the substring S[l,r].
Attantion, each same palindromic substring can only be counted once.
 

Input
First line contains T denoting the number of testcases.
T testcases follow. For each testcase:
First line contains a string S. We ensure that it is contains only with lower case letters.
Second line contains a interger Q, denoting the number of queries.
Then Q lines follow, In each line there are two intergers l,r, denoting the substring which is queried.
1T10, 1length1000, 1Q100000, 1lrlength
 

Output
For each testcase, output the answer in Q lines.
 

Sample Input
 
   
1 abba 2 1 2 1 3
 

Sample Output
 
   
2 3
Hint
In first query, the palindromic substrings in the substring $S[1,2]$ are "a","b". In second query, the palindromic substrings in the substring $S[1,2]$ are "a","b","bb". Note that the substring "b" appears twice, but only be counted once. You may need an input-output optimization.
 

Source
BestCoder Round #78 (div.2)
 

Recommend
wange2014   |   We have carefully selected several similar problems for you:   5694  5693  5692  5689  5687 
给定一个串,询问l到r右多少本质不同的回文串。
回文树
#include
#include
#include
#include
#include
#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;
}

 

你可能感兴趣的:(回文树)