看了解题报告才弄清楚状态转移方程:
Let isPal[i][j] be 1 if s[i...j] is palindrome, otherwise, set it 0. Let's define dp[i][j] to be number of palindrome substrings of s[i...j]. Let's calculate isPal[i][j] and dp[i][j] in O(|S|2). First, initialize isPal[i][i] = 1 and dp[i][i] = 1. After that, loop over len which states length of substring and for each specific len, loop over start which states starting position of substring. isPal[start][start + len - 1]can be easily calculated by the following formula:
isPal[start][start+len-1] = isPal[start+1][start+len-2] & (s[start] == s[start+len-1])
After that, dp[start][start + len - 1] can be calculated by the following formula which is derived from Inc-Exc Principle.
dp[start][start+len-1] = dp[start][start+len-2] + dp[start+1][start+len-1] - dp[start+1][start+len-2] + isPal[start][start+len-1]
#include<cstdio>
#include<iostream>
#include<cstring>
#define MAXN 5001
using namespace std;
int f[MAXN][MAXN],d[MAXN][MAXN];
int main()
{
// freopen("in.txt","r",stdin);
char str[MAXN];
cin>>str;
int len=strlen(str);
memset(f,0,sizeof(f));
memset(d,0,sizeof(d));
for(int i=len-1;i>=0;i--)
{
f[i][i]=1;
f[i][i-1]=1;
for(int j=i+1;j<len;j++)
{
if(str[j]==str[i]&&f[i+1][j-1])
f[i][j]=1;
}
}
for(int i=len-1;i>=0;i--)
{
d[i][i]=1;
for(int j=i+1;j<len;j++)
{
d[i][j]=d[i+1][j]+d[i][j-1]-d[i+1][j-1];
if(f[i][j])
d[i][j]++;
}
}
int n,a,b;
cin>>n;
while(n--)
{
cin>>a>>b;
cout<<d[a-1][b-1]<<endl;
}
return 0;
}