HDU5658-CA Loves Palindromic

来源:互联网 发布:mac版铃声制作软件 编辑:程序博客网 时间:2024/05/29 08:46

CA Loves Palindromic

                                                                 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
                                                                                           Total Submission(s): 499    Accepted Submission(s): 216


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
1abba21 21 3
 

Sample Output
23
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


题意:给你一个字符串,每次询问一个区间有多少种回文串

解题思路:回文树预处理出所有区间的答案


#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <map>#include <set>#include <stack>#include <queue>#include <vector>#include <bitset>#include <functional>using namespace std;#define LL long longconst int INF = 0x3f3f3f3f;const int maxn = 3e5 + 10;char s[maxn];int ans[1009][1009], m, l, r;struct PalindromicTree{const static int maxn = 3e5 + 10;int next[maxn][26], last, sz, tot;int fail[maxn], len[maxn];char s[maxn];void Clear(){len[1] = -1; len[2] = 0;fail[2] = fail[1] = 1;last = (sz = 3) - 1;tot = 0;memset(next[1], 0, sizeof(next[1]));memset(next[2], 0, sizeof(next[2]));}int Node(int length){memset(next[sz], 0, sizeof(next[sz]));len[sz] = length;return sz++;}int getfail(int x){while (s[tot] != s[tot - len[x] - 1]) x = fail[x];return x;}int add(char pos){int x = (s[++tot] = pos) - 'a', y = getfail(last);if (next[y][x]) { last = next[y][x]; return 0; }last = next[y][x] = Node(len[y] + 2);fail[last] = len[last] == 1 ? 2 : next[getfail(fail[y])][x];return 1;}}solve;int main(){int t;scanf("%d", &t);while (t--){scanf("%s", s);for (int i = 0; s[i]; i++){solve.Clear();ans[i + 1][i] = 0;for (int j = i; s[j]; j++)ans[i + 1][j + 1] = ans[i + 1][j] + solve.add(s[j]);}scanf("%d", &m);while (m--){scanf("%d%d", &l, &r);printf("%d\n", ans[l][r]);}}return 0;}