Harry and magic string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 409 Accepted Submission(s): 203
Problem Description
Harry got a string T, he wanted to know the number of T’s disjoint palindrome substring pairs. A string is considered to be palindrome if and only if it reads the same backward or forward. For two substrings of
T:x=T[a1…b1],y=T[a2…b2]
(where a1 is the beginning index of
x,b1
is the ending index of x.
a2,b2
as the same of y), if both x and y are palindromes and
b1<a2 or b2<a1
then we consider (x, y) to be a disjoint palindrome substring pair of T.
Input
There are several cases.
For each test case, there is a string T in the first line, which is composed by lowercase characters. The length of T is in the range of [1,100000].
For each test case, there is a string T in the first line, which is composed by lowercase characters. The length of T is in the range of [1,100000].
Output
For each test case, output one number in a line, indecates the answer.
Sample Input
aca aaaa
Sample Output
3 15HintFor the first test case there are 4 palindrome substrings of T. They are: S1=T[0,0] S2=T[0,2] S3=T[1,1] S4=T[2,2] And there are 3 disjoint palindrome substring pairs. They are: (S1,S3) (S1,S4) (S3,S4). So the answer is 3.
Source
Recommend
heyang
题意:给你一个字符串,求有多少个不相交的回文串对
解题思路:回文树,把字符串前后分别扫两次,建两次树即可
#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 long
const int INF = 0x3f3f3f3f;
const LL mod = 19930726;
const int maxn = 1e6 + 10;
char s[maxn];
LL a[maxn];
struct PalindromicTree
{
const static int maxn = 1e6 + 10;
int next[maxn][26], last, sz, tot;
int fail[maxn], len[maxn];
LL cnt[maxn];
char s[maxn];
void Clear()
{
len[1] = -1; len[2] = 0;
fail[2] = fail[1] = 1;
last = (sz = 3) - 1;
cnt[1] = cnt[2] = 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, cnt[sz] = 0;
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]) return cnt[last = next[y][x]];
last = next[y][x] = Node(len[y] + 2);
fail[last] = len[last] == 1 ? 2 : next[getfail(fail[y])][x];
cnt[last] += 1 + cnt[fail[last]];
return cnt[last];
}
}solve;
int main()
{
while (~scanf("%s", s))
{
solve.Clear();
LL ans = a[0] = 0, len = strlen(s);
for (int i = 0; i < len; i++) a[i + 1] = a[i] + solve.add(s[i]);
solve.Clear();
for (int i = len - 1; i >= 0; i--) ans += solve.add(s[i])*a[i];
printf("%lld\n", ans);
}
return 0;
}