题意:
[a,b] [x, y]为回文串,a<=b<x<=y。现在问像这样的回文串组有几组。
思路:
本来没什么思路的,重新做了一遍最长回文子串长度,有点想法。
在求回文子串时,每当遇到一个子串是回文子串,就记录下这个回文串的左下标l和右下标r。
并且用rec[i]记录以i作为左下标的回文串个数。
枚举回文串,假设当前的回文串范围为[l, r],则加上左下标>=(r+1)的回文串个数。
code:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAXN = 2005;
const int INF = 0x3f3f3f3f;
struct PP {
int l, r;
}p[MAXN*MAXN];
bool dp[MAXN][MAXN];
char ch[MAXN];
int rec[MAXN]; //rec[i]:记录以i为左下标的回文串个数。
LL sum[MAXN]; //sum[i]:记录以<=i为左下标的回文串个数。
int main() {
scanf("%s", ch+1);
int len = strlen(ch+1);
//init
int cnt = 0;
for(int i = 1;i <= len; i++) {
dp[i][i] = true;
rec[i]++;
p[cnt++] = (PP){i, i};
}
for(int i = 1;i+1 <= len; i++) {
if(ch[i] == ch[i+1]) {
dp[i][i+1] = true;
rec[i]++;
p[cnt++] = (PP){i, i+1};
}
}
//palindrome
for(int i = 3;i <= len; i++) {
for(int j = 1;j+i-1 <= len; j++) {
if(ch[j] == ch[j+i-1] && dp[j+1][j+i-2]) {
dp[j][j+i-1] = true;
rec[j]++;
p[cnt++] = (PP){j, j+i-1};
}
}
}
//count
for(int i = 1;i <= len; i++)
sum[i] = sum[i-1]+rec[i];
LL res = 0;
for(int i = 0;i < cnt; i++)
res += sum[len] - sum[p[i].r];
printf("%I64d\n", res);
return 0;
}